0

I am using the following way but I got an error

 public static void main(String[] args) {
    ArrayList<Integer> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    list.add(3);
    list.add(4);
    list.add(5);
    list.add(5);

    int[] arr = list.toArray();
}

The error I got is

java: incompatible types: java.lang.Object[] cannot be converted to int[]

2 Answers2

1

You should be able to use another option of toArray method which takes empty array as argument.

Integer[] arr =  new Integer[list.size()];
list.toArray(arr);
      

Integer class support all operations available for int data type

Milind Barve
  • 410
  • 3
  • 5
1

toArray() method returns an array of type Object(Object[]). We need to typecast it to Integer before using as Integer objects. If we do not typecast, we get compilation error.

This would work fine

Object[] objects = list.toArray();

For getting directly int array, you can use streams() method of list and mapToInt() to convert ArrayList to array of primitive data type int

int[] arr = list.stream().mapToInt(i -> i).toArray();
kehsihba19
  • 83
  • 6