Guava Bytes類

Bytes是byte的基本類型實用工具類。

類聲明

以下是com.google.common.primitives.Bytes類的聲明:

@GwtCompatible public final class Bytes extends Object

方法:

S.N.

方法及說明

1

static List asList(byte... backingArray)
返回由指定數組支持的固定大小的列表,類似 Arrays.asList(Object[]).

2

static byte[] concat(byte[]... arrays)
則返回來自每個陣列提供組合成一個單一的陣列值。

3

static boolean contains(byte[] array, byte target)
返回true,如果目標是否存在在任何地方數組元素。

4

static byte[] ensureCapacity(byte[] array, int minLength, int padding)
返回一個包含相同的值數組的數組,但保證是一個規定的最小長度。

5

static int hashCode(byte value)
返回哈希碼的值;等於調用的結果 ((Byte) value).hashCode().

6

static int indexOf(byte[] array, byte target)
返回目標數組的首次出現的索引值。

7

static int indexOf(byte[] array, byte[] target)
返回指定目標的第一個匹配的起始位置數組內,或-1如果不存在。

8

static int lastIndexOf(byte[] array, byte target)
返回目標在數組中最後一個出場的索引的值。

9

static byte[] toArray(Collection<? extends Number> collection)
返回包含集合的每個值的數組,轉換爲字節值中的方式Number.byteValue().

繼承的方法

這個類繼承了以下類方法:

  • java.lang.Object

Bytes 示例

使用所選擇的編輯器創建下面的java程序 C:/> Guava

GuavaTester.java

import java.util.List; import com.google.common.primitives.Bytes; public class GuavaTester { public static void main(String args[]){ GuavaTester tester = new GuavaTester(); tester.testBytes(); } private void testBytes(){ byte[] byteArray = {1,2,3,4,5,5,7,9,9}; //convert array of primitives to array of objects List<Byte> objectArray = Bytes.asList(byteArray); System.out.println(objectArray.toString()); //convert array of objects to array of primitives byteArray = Bytes.toArray(objectArray); System.out.print("[ "); for(int i = 0; i< byteArray.length ; i++){ System.out.print(byteArray[i] + " "); } System.out.println("]"); byte data = 5; //check if element is present in the list of primitives or not System.out.println("5 is in list? "+ Bytes.contains(byteArray, data)); //Returns the index System.out.println("Index of 5: " + Bytes.indexOf(byteArray,data)); //Returns the last index maximum System.out.println("Last index of 5: " + Bytes.lastIndexOf(byteArray,data)); } }

驗證結果

使用javac編譯器編譯如下類

C:\Guava>javac GuavaTester.java

現在運行GuavaTester看到的結果

C:\Guava>java GuavaTester

看到結果。

[1, 2, 3, 4, 5, 5, 7, 9, 9]
[ 1 2 3 4 5 5 7 9 9 ]
5 is in list? true
Index of 5: 4
Last index of 5: 5