字节类 |番石榴 |Java
Bytes是原始类型字节的实用程序类。它提供了与字节原语有关的静态实用程序方法,这些方法在字节或数组中都没有,并将字节解释为既无符号也无符号。在SignedBytes和UnsignedBytes中可以找到专门将字节视为有符号或无符号的方法。
宣言 :
@GwtCompatible(emulated=true)
public final class Bytes
extends Object
下表显示了 Guava Bytes Class 提供的方法:
例外:
- ensureCapacity : IllegalArgumentException如果 minLength 或 padding 为负数。
- toArray : NullPointerException如果集合或其任何元素为空。
下面给出了一些示例,展示了 Guava Bytes Class 方法的实现:
示例 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 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