Guava - 位元組類



Bytes 是一個用於基本型別 byte 的工具類。

類宣告

以下是 com.google.common.primitives.Bytes 類的宣告:

@GwtCompatible
public final class Bytes
   extends Object

方法

序號 方法及描述
1

static List<Byte> 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)

返回 value 的雜湊碼;等於呼叫 ((Byte) value).hashCode() 的結果。

6

static int indexOf(byte[] array, byte target)

返回 target 在陣列中第一次出現時的索引。

7

static int indexOf(byte[] array, byte[] target)

返回陣列中指定目標第一次出現的起始位置,如果不存在則返回 -1。

8

static int lastIndexOf(byte[] array, byte target)

返回 target 在陣列中最後一次出現時的索引。

9

static byte[] toArray(Collection<? extends Number> collection)

返回一個包含集合中每個值的陣列,以 Number.byteValue() 的方式轉換為 byte 值。

繼承的方法

此類繼承自以下類:

  • 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
guava_primitive_utilities.htm
廣告

© . All rights reserved.