Guava Bytes类

来源:这里教程网 时间:2026-02-17 21:39:15 作者:

Guava Bytes类

Bytes是一种用于原始类型byte的实用类。

类声明

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

@GwtCompatiblepublic final class Bytes   extends Object

方法

序号方法 & 描述
1static List asList(byte… backingArray) 返回由指定数组支持的固定大小的列表,类似于Arrays.asList(Object[])。
2static byte[] concat(byte[]… arrays) 将每个提供的数组的值合并为一个数组返回。
3static boolean contains(byte[] array, byte target) 如果目标在数组中作为元素出现,则返回true。
4static byte[] ensureCapacity(byte[] array, int minLength, int padding) 返回一个包含与数组相同值的数组,但保证至少具有指定的最小长度。
5static int hashCode(byte value) 返回值的哈希码;等同于调用((Byte) value).hashCode()的结果。
6static int indexOf(byte[] array, byte target) 返回目标值在数组中第一次出现的索引。
7static int indexOf(byte[] array, byte[] target) 返回指定目标在数组中首次出现的起始位置,如果不存在则返回-1。
8static int lastIndexOf(byte[] array, byte target) 返回目标值在数组中最后一次出现的索引。
9static 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? trueIndex of 5: 4Last index of 5: 5

相关推荐