Guava - Bytes Class


Bytes is a utility class for primitive type byte.

Class Declaration

Following is the declaration for class −

public final class Bytes
   extends Object


Sr.No Method & Description

static List<Byte> asList(byte... backingArray)

Returns a fixed-size list backed by the specified array, similar to Arrays.asList(Object[]).


static byte[] concat(byte[]... arrays)

Returns the values from each provided array combined into a single array.


static boolean contains(byte[] array, byte target)

Returns true if the target is present as an element anywhere in array.


static byte[] ensureCapacity(byte[] array, int minLength, int padding)

Returns an array containing the same values as the array, but guaranteed to be of a specified minimum length.


static int hashCode(byte value)

Returns a hash code for value; equal to the result of invoking ((Byte) value).hashCode().


static int indexOf(byte[] array, byte target)

Returns the index of the first appearance of the value target in array.


static int indexOf(byte[] array, byte[] target)

Returns the start position of the first occurrence of the specified target within the array, or -1 if there is no such occurrence.


static int lastIndexOf(byte[] array, byte target)

Returns the index of the last appearance of the value target in array.


static byte[] toArray(Collection<? extends Number> collection)

Returns an array containing each value of collection, converted to a byte value in the manner of Number.byteValue().

Methods Inherited

This class inherits methods from the following class −

  • java.lang.Object

Example of Bytes Class

Create the following java program using any editor of your choice in say C:/> Guava.

import java.util.List;

public class GuavaTester {
   public static void main(String args[]) {
      GuavaTester tester = new GuavaTester();

   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);

      //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] + " ");

      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));

Verify the Result

Compile the class using javac compiler as follows −


Now run the GuavaTester to see the result.

C:\Guava>java GuavaTester

See the result.

[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