对象到ArrayList <string> unchecked cast </string>

时间:2012-10-23 10:37:29

标签: java arraylist iterator

使用-Xlint编译我的代码我发现了这个:

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

这是代码:

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;     
}

应该如何完成演员表?

3 个答案:

答案 0 :(得分:4)

你的迭代器也需要一个类型,如下:

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();
}

另一方面,最好是编程接口,而不是实现。因此,你写道:

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();
}

答案 1 :(得分:2)

你的迭代器应该是

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

顺便说一句,你可以使用for-each循环:

for (ArrayList<String> sublist : msg) {
    ....            
}

答案 2 :(得分:1)

ArrayList<ArrayList<String>> msg = new ArrayList<ArrayList<String>>();
//add some data to msg
for (ArrayList<String> msgData : msg) {
   //do something
}