LinkedHashSet的子类没有for循环?

时间:2018-11-20 16:03:55

标签: java for-loop generic-collections

我正在使用一个扩展LinkedHashSet的集合类。通过迭代器或forEach遍历此集合的效果很好,但简单的for循环则无法实现。我在做什么错了?

public class MySet<E> extends LinkedHashSet
{
    //..........
}


MySet<String> serie = new MySet();

// this doesn't work: Incompatible types: Object cannot be converted to String                                  
for (String entry : serie) {                                     
    System.out.println(entry);                              
}                                       

// this works 
serie.forEach((entry) -> {                      
    System.out.println(entry);
});

// this works too
for (Iterator<String> it = serie.iterator(); it.hasNext();) {   
    String entry = it.next();
    System.out.println(entry);
}

0 个答案:

没有答案