1
public class Main {

public static void main(String[] args) {
    byte[] a=new byte[3];
    List<Byte> c=new ArrayList<Byte>();

    c.addAll(Arrays.asList(a)); 
    //The method addAll(Collection<? extends Byte>) in the type List<Byte> 
    //is not applicable for the arguments (List<byte[]>)

    Collections.addAll(c, a);
    //The method addAll(Collection<? super T>, T...) in the type Collections 
    //is not applicable for the arguments (List<Byte>, byte[])

}

}

Last two lines give compile error.

To fix it, firstly I read this Create ArrayList from array discussing. I try this solution, but it don't work. Here Converting array to list in Java is explain, why it don't work, but isn't solution.

"source array is a primitive array of bytes, instead of Byte objects" is true, and I hope, that exists more beautibul solution, then iterate and cast each element.

2
  • How about Byte[]? There are very many threads here that discusses different workarounds and solutions. Commented Jul 6, 2014 at 20:39
  • Instead of a List<Byte>, consider using a ByteBuffer. It's not identical to a List, but it does represent a sequence of primitive byte values and it includes, among other things, a method to add every element of an array of bytes. Commented Jul 6, 2014 at 22:29

5 Answers 5

1

Your array must be an array of Byte, not byte. addAll requires a collection of objects that match.

In other words: Byte[] a=new Byte[3];

Alternatively, if your source array is a primitive array of bytes, instead of Byte objects, then you have to loop through them and add one at a time:

for( byte toInsert: a ){
   c.add((Byte)a);// Probably don't need the cast, but included for clarity
}
Sign up to request clarification or add additional context in comments.

Comments

0

It is not possible with standard Java to have Collections on primitive types. However there are some libraries available (like trove or apache commons primitives) to achieve this.

This has great performance implications. The Boxed Types of the primitives have a massive amount of (mostly unneeded) overhead, because every boxed object extends the java basic Object (i think the overhead is somewhere at 8 bytes per object). I a List with for instance 1000 Integers you have 1000 times the overhead, which can be bad for your memory. So if memory consumption is an issue, primitive collections are a great way to deal with it.

If Memory conspumtion is not a problem, you can use the boxed types and jazees answer

Comments

0

With Java 8 you can use streams do it in a single statement, without the casting and iteration you want to avoid:

byte[] byteArray = {-128, 89, 103, 92, 0, 127};
List<Byte> byteList = IntStream.range(0, byteArray.length) 
                               .mapToObj((int i) -> byteArray[i]) 
                               .collect(Collectors.toList()); 
System.out.println("byteList = " + byteList);

The basic idea is to get the array values into a Stream, then load those stream values into a List:

  • range() yields an IntStream 0,1,2,3,4,5 corresponding to the index
    values in the byte array.
  • mapToObj() yields a Stream -128, 89, 103, 92, 0, 127 corresponding to the byte array's values.
  • collect() puts those stream values into a List.

You can use the same approach for char[] and short[] transformations.

Comments

0

In Java, there are classes that "wrap" around primitive types, so to speak. These classes are: Integer, Byte, Long, Double, Float, Character, etc.

Now here are the primitive types: int, byte, long, double, float, char, etc.

You see the similarity? So when you are using type parameters (notated like this: ), you have to use these wrapper classes instead of the primitive types because primitives aren't classes (that's why String isn't a primitive but it is a class.) You can add primitive types like "byte b = 1" to the list you have up there, but because the array you have doesn't match the class of your list, it doesn't work.

It's an easy fix, just changed the type of your array from "byte" to "Byte."

Comments

0

The simple way I would recommend to new programmers:

static ArrayList<Integer> primitiveArrayToArrayList(int[] input)
{
    ArrayList<Integer> result = new ArrayList<>();
    for (int i : input)
        result.add(i);
    return result;
}

The modern way I would recommend to advanced programmers:

static ArrayList<Integer> primitiveArrayToArrayList(int[] input)
{
    return Arrays.stream(input).boxed().collect(Collectors.toCollection(ArrayList::new));
}

note: Arrays.stream() is only available for int, long, double and reference types

This way allows simple modifications in a more complex use case, like here:

static ArrayList<Integer> findValues(int[] input, Predicate<Integer> filter, int limit)
{
    return Arrays.stream(input).boxed().filter(filter).limit(limit).collect(Collectors.toCollection(ArrayList::new));
}

public static void main(String[] args)
{
    int[] values = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    Predicate<Integer> filter = i -> i % 2 == 0;
    int limit = 3;

    System.out.println(findValues(values, filter, limit));
}

converting the Array to an ArrayList, while filtering for even numbers and limit the result size to 3 results in:

out: [0, 2, 4]

Stream API chain vs. loop

static ArrayList<Integer> findValues(int[] input, Predicate<Integer> filter, int limit)
{
    return Arrays.stream(input).boxed().filter(filter).limit(limit).collect(Collectors.toCollection(ArrayList::new));
}

static ArrayList<Integer> findValues(int[] input, Predicate<Integer> filter, int limit)
{
    ArrayList<Integer> integers = new ArrayList<>();
    for (int i : input)
    {
        if (filter.test(i))
        {
            if (limit-- == 0) break;
            integers.add(i);
        }
    }
    return integers;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.