Guava - Bytes 类
Bytes 是基本类型字节的实用程序类。
类声明
以下是 com.google.common.primitives.Bytes 类的声明 −
@GwtCompatible public final class Bytes extends Object
方法
| Sr.No | 方法及描述 |
|---|---|
| 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
Example of Bytes Class
使用您在 C:/> Guava 中选择的任何编辑器创建以下 java 程序。
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.html

