Java Bytes类
Bytes 是原始类型字节的一个实用类。它提供了与字节基元有关的 静态实用方法 ,这些 方法 在Byte或Arrays中都没有找到,并且将字节解释为有符号或无符号。具体将字节视为有符号或无符号的方法见于 SignedBytes 和 UnsignedBytes。
声明 :
@GwtCompatible(emulated=true)
public final class Bytes
extends Object
下表显示了Guava Bytes类所提供的方法。
异常。
- ensureCapacity : 如果minLength或padding为负数,则出现IllegalArgumentException。
- toArray: 如果集合或其任何元素为空,则出现NullPointerException。
下面给出了一些例子,显示了Guava Bytes类方法的实现:
例1 :
// Java code to show implementation
// of Guava Bytes.asList() method
import com.google.common.primitives.Bytes;
import java.util.*;
class GFG {
// Driver method
public static void main(String[] args)
{
byte arr[] = { 3, 4, 5, 6, 7 };
// Using Bytes.asList() method which convert
// array of primitives to array of objects
List<Byte> myList = Bytes.asList(arr);
// Displaying the elements
System.out.println(myList);
}
}
输出:
[3, 4, 5, 6, 7]
例2 :
// Java code to show implementation
// of Guava Bytes.indexOf() method
import com.google.common.primitives.Bytes;
import java.util.*;
class GFG {
// Driver method
public static void main(String[] args)
{
byte[] arr = { 3, 4, 5, 6, 7 };
// Displaying the index for
// first occurrence of given target
System.out.println(Bytes.indexOf(arr, (byte)5));
}
}
输出:
2
例3 :
// Java code to show implementation
// of Guava Bytes.concat() method
import com.google.common.primitives.Bytes;
import java.util.*;
class GFG {
// Driver method
public static void main(String[] args)
{
byte[] arr1 = { 3, 4, 5 };
byte[] arr2 = { 6, 7 };
// Using Bytes.concat() method which
// combines arrays from specified
// arrays into a single array
byte[] arr = Bytes.concat(arr1, arr2);
// Displaying the elements
System.out.println(Arrays.toString(arr));
}
}
输出:
[3, 4, 5, 6, 7]
例4 :
// Java code to show implementation
// of Guava Bytes.contains() method
import com.google.common.primitives.Bytes;
class GFG {
// Driver method
public static void main(String[] args)
{
byte[] arr = { 3, 4, 5, 6, 7 };
// Using Bytes.contains() method which
// checks if element is present in array
// or not
System.out.println(Bytes.contains(arr, (byte)8));
System.out.println(Bytes.contains(arr, (byte)7));
}
}
产出 :
false
true
例5 :
// Java code to show implementation
// of Guava Bytes.lastIndexOf() method
import com.google.common.primitives.Bytes;
class GFG {
// Driver method
public static void main(String[] args)
{
byte[] arr = { 3, 4, 5, 6, 7, 5, 5 };
// Using Bytes.lastIndexOf() method
// to get last occurrence of given target
System.out.println(Bytes.lastIndexOf(arr, (byte)5));
}
}
输出:
6
例6 :
// Java code to show implementation
// of Guava Bytes.lastIndexOf() method
import com.google.common.primitives.Bytes;
class GFG {
// Driver method
public static void main(String[] args)
{
byte[] arr = { 3, 4, 5, 6, 7, 5, 5 };
// Using Bytes.lastIndexOf() method
// to get last occurrence of given target
// here target i.e, 9 is not present in
// array arr, so -1 will be returned
System.out.println(Bytes.lastIndexOf(arr, (byte)9));
}
}
输出:
-1