-5

The error is, that it is showing a red line in Collections.addAll(in,n). How do I solve this?

ArrayList<Integer> in = new ArrayList<>(); //declared array in integer type
int[] n = getResources().getIntArray(R.array.number12);
Collections.addAll(in,n); //this is not working showing error,it is not accepting

integers.xml

<resources>
    <integer-array name="number12">
        <item>735895698</item>`
        <item>814895046</item>``
    </integer-array>
</resources>
2
  • 1
    maybe this can help you in.addAll(Arrays.stream(n).boxed().collect(Collectors.toList())); Commented Jun 14, 2018 at 13:11
  • 1
    Possible duplicate of Assigning an array to an ArrayList in Java Commented Jun 14, 2018 at 13:11

2 Answers 2

1

This doesn't work, because an int[]-array is not an Integer[]-array, which Collections.addAll() expectes.

here are two ways to create a list from an array. This uses a for-each loop which iterates over the array and then adds every int in the array to the list:

int[] n = getResources().getIntArray(R.array.number12);
List<Integer> list = new ArrayList<>(n.length);

for(int i : n){
    list.add(i);
}

The other way, is to use the in Java8 introduced Arrays.stream():

int[] n = getResources().getIntArray(R.array.number12);
List<Integer> list = Arrays.stream(n)
    .boxed()
    .collect(Collectors.toList());

And if you explicitly want to get an ArrayList you can use the following:

int[] n = getResources().getIntArray(R.array.number12);
List<Integer> list = Arrays.stream(n)
    .boxed()
    .collect(Collectors.toCollection(ArrayList::new));
Sign up to request clarification or add additional context in comments.

1 Comment

OP suggestion actually works. It's just the type needs to be the same. The Collection expect an array of Integer not an array of int
1

Quick fix:

ArrayList<Integer> in= new ArrayList<>();//declared array in integer type
Integer[] n=getResources().getIntArray(R.array.number12);
Collections.addAll(in,n);//this is not working showing error,it is not 

As explained here, the type needs to be the same. The Collection expects an array of Integer, not an array of int

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.