5

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

演员应该怎么做?

4

3 回答 3

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();
}
于 2012-10-23T10:40:56.217 回答
2

您的迭代器应该类似于

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

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

for (ArrayList<String> sublist : msg) {
    ....            
}
于 2012-10-23T10:39:27.163 回答
1
ArrayList<ArrayList<String>> msg = new ArrayList<ArrayList<String>>();
//add some data to msg
for (ArrayList<String> msgData : msg) {
   //do something
}
于 2012-10-23T10:41:52.270 回答