---
title: "guava笔记8-Primitives"
author: "leadtoit"
date: "2013-10-22T13:38:42Z"
tags: []
categories: ["编程语言"]
slug: "guava-8-primitives"
draft: false
lastmod: "2013-10-21T17:56:09Z"
id: 1961745
url: "https://leadtoit.iteye.com/blog/1961745"
---

Java有8中基本数据类型：byte ，short，int，long，float，double，char，boolean。  
Java并不存在unsigned类型，guava新定义了UnsignedInteger 和 UnsignedLong 分别表示int和long的无符号类型。

在com.google.common.primitives中提供了一些util类来对基本类型进行操作。

 

byte

[Bytes](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/primitives/Bytes.html), [SignedBytes](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/primitives/SignedBytes.html), [UnsignedBytes](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/primitives/UnsignedBytes.html)

short

[Shorts](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/primitives/Shorts.html)

int

[Ints](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/primitives/Ints.html), [UnsignedInts](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/primitives/UnsignedInts.html)

long

[Longs](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/primitives/Longs.html),[UnsignedLongs](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/primitives/UnsignedLongs.html)

float

[Floats](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/primitives/Floats.html)

double

[Doubles](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/primitives/Doubles.html)

char

[Chars](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/primitives/Chars.html)

boolean

[Booleans](http://docs.guava-libraries.googlecode.com/git-history/release/javadoc/com/google/common/primitives/Booleans.html)

针对byte，提供了Bytes， SignedBytes, UnsignedBytes三个帮助类，分别针对不关心符号，有符号，无符号三种类型的byte数据。Bytes里面的方法很基本，无论有无符号，都能使用。

针对int和long，提供了Xxxs及UnsignedXxxs分别对有符号和无符号的类型进行处理。

这些util类主要提供的方法包括：  
**（1）对数组进行操作：**  
asList：把数组转换为对应的List。  
toArray：把集合转化为数组  
concat：把多个数组合并为一个数组  
contains：判断数组中是否包含元素  
indexOf：查找数组中元素出现的位置  
lastIndexOf：查找数组总元素最后出现的位置  
min：查找数组中最小的元素  
max：查找元素中最大的元素  
join：把数组按指定分隔符拼接为字符串  
lexicographicalComparator：字典序比较器

**（2）与字节数组相互转换：（big-endian存储法）**  
常量BYTES：表示这种类型需要多少个字节来表示  
fromByteArray：从字节数组转化为该类型数据  
fromBytes：同上，不过参数类型是变长字节  
toByteArray：转换为字节数组

**（3）比较及转换：**  
compare：比较大小  
Ints.checkedCast：把long转化为int，超过范围则抛异常  
Ints.saturatedCast：把long转化为int，超过范围则用最接近的int替代

**（4）UnsignedInteger和UnsignedLong类型特有的方法：**  
add加法  
Subtract 减法  
multiply 乘法  
divide 除法  
remainder 取余  
valueOf bigint或者long转换为无符号类型  
asUnsigned 基本数据转换为无符号类型  
bigIntegerValue：转换为bigint  
parseUnsignedXxx：字符串转化为无符号数据  
toString：无符号数据转化为字符串