Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

object to ArrayList<String> unchecked cast

Compiling my code with -Xlint I found this:

warning: [unchecked] unchecked cast
found   : java.lang.Object
required: java.util.ArrayList<java.lang.String>
                    ArrayList<String> msgData = (ArrayList<String>)element;

This is the code:

ArrayList<ArrayList<String>> msg = new ArrayList<ArrayList<String>>();
//add some data to msg
Iterator i = msg.iterator();
while(i.hasNext()) {

    Object element = i.next();
    ArrayList<String> msgData = (ArrayList<String>)element;     
}

how should the cast be done?

like image 215
user1256477 Avatar asked Oct 23 '12 10:10

user1256477


3 Answers

Your iterator should be something like

Iterator<ArrayList<String>> i = msg.iterator();

Btw you can use for-each loop for it:

for (ArrayList<String> sublist : msg) {
    ....            
}
like image 40
zvez Avatar answered Oct 20 '22 04:10

zvez


Your Iterator needs a type as well, like this:

ArrayList<ArrayList<String>> msg = new ArrayList<ArrayList<String>>();
//add some data to msg
Iterator<ArrayList<String>> i = msg.iterator();
while(i.hasNext()) {
    ArrayList<String> element = i.next();
}

On a side note, it's better to program to interfaces, not to implementations. Thus, you'd write:

List<List<String>> msg = new ArrayList<List<String>>();
//add some data to msg
Iterator<List<String>> i = msg.iterator();
while(i.hasNext()) {
    List<String> element = i.next();
}
like image 156
mthmulders Avatar answered Oct 20 '22 04:10

mthmulders


ArrayList<ArrayList<String>> msg = new ArrayList<ArrayList<String>>();
//add some data to msg
for (ArrayList<String> msgData : msg) {
   //do something
}
like image 1
Kerb Avatar answered Oct 20 '22 05:10

Kerb