2012-10-23 65 views
5

編譯代碼才能使用-Xlint我發現這一點:對象ArrayList的<String>選中投

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

你的迭代器需要一個類型爲好,像這樣:

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

你的迭代器應該是這樣的

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

順便說一句,你可以使用for-each循環吧:

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