com.google.common.primitives.Ints
官方文檔:Primitives
Ints提供了一些靜態工具方法,正如官方文檔所說:
These types cannot be used as objects or as type parameters to generic types, which means that many general-purpose utilities cannot be applied to them. Guava provides a number of these general-purpose utilities, ways of interfacing between primitive arrays and collection APIs, conversion from types to byte array representations, and support for unsigned behaviors on certain types.
這些類型(Bytes
, SignedBytes
, UnsignedBytes
,Shorts
,Ints
, UnsignedInteger
, UnsignedInts
,Longs
, UnsignedLong
, UnsignedLongs
,Floats
,Doubles
,Chars
,Booleans
)不能用作對象或者是類型參數,而是以靜態方法的形式提供了一些使用的工具,包括:
- 數組和集合類型之間的轉換
- 從類型到字節數組的轉換
- 某些情形的無符號行為
所以Ints中除了定義了一系列靜態工具方法和實行這些方法所需要的靜態變量之外, 沒有其他內容,所以我們的學習重點應該在這些工具方法的實現上。
1、checkedCast方法
/**
* Returns the {@code int} value that is equal to {@code value}, if possible.
*
* @param value any value in the range of the {@code int} type
* @return the {@code int} value that equals {@code value}
* @throws IllegalArgumentException if {@code value} is greater than {@link Integer#MAX_VALUE} or
* less than {@link Integer#MIN_VALUE}
*/
public static int checkedCast(long value) {
int result = (int) value;
if (result != value) {
// don't use checkArgument here, to avoid boxing
throw new IllegalArgumentException("Out of range: " + value);
}
return result;
}
進行類型轉換:將long類型的輸入參數轉換為int類型的返回,前提是long類型的值沒有超過int的可表示范圍,這里有兩個點需要關注:
- (1)強制類型轉換,通過比較值是不是和原值相等來判斷是否轉換成功;
- (2)避免不必要的裝箱(boxing)操作
2、toByteArray方法
將一個整形value轉換為大端表示,以byte array返回,array中每個值有4位。
/**
* Returns a big-endian representation of {value} in a 4-element byte array; equivalent to
* {@code ByteBuffer.allocate(4).putInt(value).array()}.
* For example, the input value
* {@code 0x12131415} would yield the byte array {@code {0x12, 0x13, 0x14, 0x15}}.
*
* <p>If you need to convert and concatenate several values (possibly even of different types),
* use a shared {@link java.nio.ByteBuffer} instance, or use
* {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer.
*/
@GwtIncompatible // doesn't work
public static byte[] toByteArray(int value) {
return new byte[] {
(byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value
};
}
3、join方法
將整形數組里的所有元素之間,用一個separator連接起來,返回連接后形成的String,實現也相對比較簡單。
/**
* Returns a string containing the supplied {@code int} values separated by {@code separator}. For
* example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}.
*
* @param separator the text that should appear between consecutive values in the resulting string
* (but not at the start or end)
* @param array an array of {@code int} values, possibly empty
*/
public static String join(String separator, int... array) {
checkNotNull(separator);
if (array.length == 0) {
return "";
}
// For pre-sizing a builder, just get the right order of magnitude
StringBuilder builder = new StringBuilder(array.length * 5);
builder.append(array[0]);
for (int i = 1; i < array.length; i++) {
builder.append(separator).append(array[i]);
}
return builder.toString();
}
- 重點在:用StringBuilder進行字符串拼接。
4、asList方法
這個方法比較有意思。它的功能是將給定的整形數組轉換為List<Integer>,有以下幾點需要關注:
- 我預想這個方法的設計是:創建List,遍歷數組,然后逐個裝箱,將這個List返回即可。但是實際上并沒有這么做,而是專門聲明了一個內部類IntArrayAsList,這個類繼承自List的抽象類AbstractList,通過構造方法參數將需要轉換的array傳入,同時實現了相關的List方法,如size()、isEmpty()、get(int index)等。
/**
* Returns a fixed-size list backed by the specified array, similar to
* {@link Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any
* attempt to set a value to {@code null} will result in a {@link NullPointerException}.
*
* <p>The returned list maintains the values, but not the identities, of {@code Integer} objects
* written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for
* the returned list is unspecified.
*
* @param backingArray the array to back the list
* @return a list view of the array
*/
public static List<Integer> asList(int... backingArray) {
if (backingArray.length == 0) {
return Collections.emptyList();
}
return new IntArrayAsList(backingArray);
}
// 內部類
@GwtCompatible
private static class IntArrayAsList extends AbstractList<Integer>
implements RandomAccess, Serializable {
final int[] array;
final int start;
final int end;
IntArrayAsList(int[] array) {
this(array, 0, array.length);
}
IntArrayAsList(int[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override
public int size() {
return end - start;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Integer get(int index) {
checkElementIndex(index, size());
return array[start + index];
}
@Override
public boolean contains(Object target) {
// Overridden to prevent a ton of boxing
return (target instanceof Integer) && Ints.indexOf(array, (Integer) target, start, end) != -1;
}
@Override
public int indexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Integer) {
int i = Ints.indexOf(array, (Integer) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override
public int lastIndexOf(Object target) {
// Overridden to prevent a ton of boxing
if (target instanceof Integer) {
int i = Ints.lastIndexOf(array, (Integer) target, start, end);
if (i >= 0) {
return i - start;
}
}
return -1;
}
@Override
public Integer set(int index, Integer element) {
checkElementIndex(index, size());
int oldValue = array[start + index];
// checkNotNull for GWT (do not optimize)
array[start + index] = checkNotNull(element);
return oldValue;
}
@Override
public List<Integer> subList(int fromIndex, int toIndex) {
int size = size();
checkPositionIndexes(fromIndex, toIndex, size);
if (fromIndex == toIndex) {
return Collections.emptyList();
}
return new IntArrayAsList(array, start + fromIndex, start + toIndex);
}
@Override
public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof IntArrayAsList) {
IntArrayAsList that = (IntArrayAsList) object;
int size = size();
if (that.size() != size) {
return false;
}
for (int i = 0; i < size; i++) {
if (array[start + i] != that.array[that.start + i]) {
return false;
}
}
return true;
}
return super.equals(object);
}
@Override
public int hashCode() {
int result = 1;
for (int i = start; i < end; i++) {
result = 31 * result + Ints.hashCode(array[i]);
}
return result;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder(size() * 5);
builder.append('[').append(array[start]);
for (int i = start + 1; i < end; i++) {
builder.append(", ").append(array[i]);
}
return builder.append(']').toString();
}
int[] toIntArray() {
// Arrays.copyOfRange() is not available under GWT
int size = size();
int[] result = new int[size];
System.arraycopy(array, start, result, 0, size);
return result;
}
private static final long serialVersionUID = 0;
}
5、lexicographicalComparator方法
lexicographicalComparator方法會返回一個比較器,按照一個特定的規則來比較兩個整型數組的大小,我這里并不想重點研究這個比較規則,而是關注這個方法的實現過程中一個關于枚舉的巧妙用法。
/**
* Returns a comparator that compares two {@code int} arrays <a
* >lexicographically</a>. That is, it
* compares, using {@link #compare(int, int)}), the first pair of values that follow any common
* prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For
* example, {@code [] < [1] < [1, 2] < [2]}.
*
* <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays
* support only identity equality), but it is consistent with {@link Arrays#equals(int[], int[])}.
*
* @since 2.0
*/
public static Comparator<int[]> lexicographicalComparator() {
return LexicographicalComparator.INSTANCE;
}
private enum LexicographicalComparator implements Comparator<int[]> {
INSTANCE;
@Override
public int compare(int[] left, int[] right) {
int minLength = Math.min(left.length, right.length);
for (int i = 0; i < minLength; i++) {
int result = Ints.compare(left[i], right[i]);
if (result != 0) {
return result;
}
}
return left.length - right.length;
}
@Override
public String toString() {
return "Ints.lexicographicalComparator()";
}
}
-
枚舉實現接口
枚舉LexicographicalComparator實現了Comparator接口,重寫了compare和toString方法,通過這種方式返回了一個Comparator比較器INSTANCE。
這種做法興許有些花哨,不走尋常路,完全可以用普通方式來實現這個比較器,不過這里引出了關于枚舉使用的tips:
枚舉類型可以存儲附加的數據和方法
枚舉類型可通過接口來定義行為
枚舉類型的項行為可通過接口來訪問,跟正常的 Java 類無異values() 方法可用來返回接口中的一個數組
總而言之,你可以像使用普通 Java 類一樣來使用枚舉類型。