Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 805
Bhaxy Avatar asked Jun 28 '12 06:06

Bhaxy


People also ask

Can you convert array to ArrayList?

We can convert an array to arraylist using following ways. Using Arrays. asList() method - Pass the required array to this method and get a List object and pass it as a parameter to the constructor of the ArrayList class.

What method is used to convert from an array to a list?

Answer: One of the basic methods to convert an array to a list in Java is to use the asList () method of the Arrays class. List<String> aList = Arrays. asList (myarray); Apart from this, there are more methods that convert an array to a list as discussed earlier in this tutorial.


2 Answers

Ensure you are using the correct "Arrays" import. By default, my Eclipse will try to import "edu.emory.mathcs.backport.java.util". Make sure it is just the standard "java.util" version and you should do something like:

    String[] arr = new String[]{"one", "two", "three"};
    List<String> list = Arrays.asList(arr);
like image 87
Jensen Buck Avatar answered Oct 16 '22 11:10

Jensen Buck


Collections.addAll(targetList, sourceArray); 

Try the above solution. It should work

like image 40
madhairsilence Avatar answered Oct 16 '22 11:10

madhairsilence