Bhaxy Bhaxy - 5 months ago 10
Java Question

How to convert an array to an ArrayList without warnings/errors?

So, I have a bit of a problem. I'm trying to convert an array of integers (called

list
) to an
ArrayList
(called
arrList
). The code shown below works fine:

java.util.ArrayList arrList = new java.util.ArrayList(Arrays.asList(list));


However, when compiled there is one warning: the line above is reported as using "unchecked or unsafe operations."

Unfortunately, I cannot seem to dispose of this warning. Since this is a homework assignment, part of the criteria is to be warning-free. Is there any way I could convert the array to an ArrayList without warnings/errors?

Answer

Since your list seems to be an array of int and not Integer, you need to loop over them. Try the following:

List<Integer> intList = new ArrayList<Integer>(list.length);
for (int i: list) {
  intList.add(i);
}
Comments