位置:首页 » 文章/教程分享 » Guava Bytes类

Bytes是byte的基本类型实用工具类。

类声明

以下是com.google.common.primitives.Bytes类的声明:

@GwtCompatible
public final class Bytes
   extends Object


方法:

S.N. 方法及说明
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)
返回哈希码的值;等于调用的结果 ((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