-6

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>
Lino
  • 19,604
  • 6
  • 47
  • 65
Eswar
  • 1
  • 3
  • 1
    maybe this can help you `in.addAll(Arrays.stream(n).boxed().collect(Collectors.toList()));` – Youcef LAIDANI Jun 14 '18 at 13:11
  • 1
    Possible duplicate of [Assigning an array to an ArrayList in Java](https://stackoverflow.com/questions/3746639/assigning-an-array-to-an-arraylist-in-java) – Eselfar Jun 14 '18 at 13:11

2 Answers2

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));
Lino
  • 19,604
  • 6
  • 47
  • 65
  • 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` – Eselfar Jun 14 '18 at 13:13
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

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Eselfar
  • 3,759
  • 3
  • 23
  • 43