我知道这个问题已经多次回答“如何找到”,但我还有一些问题.这是我的代码
public static void main (String [] args){
List l1= new ArrayList();
l1.add("Apple");
l1.add("Orange");
l1.add("Apple");
l1.add("Milk");
//List l2=new ArrayList();
//HashSet is a good choice as it does not allow duplicates
HashSet set = new HashSet();
for( String e: l1){
//if(!(l2).add(e)) -- did not work
if(!(set).add(e)){
System.out.println(e);
}
问题1:列表不起作用,因为List允许重复而HashSet不是 – 这是正确的假设吗?
问题2:这一行意味着什么:if(!(set).add(e))
在for循环中,我们检查String e是否在列表l1中,然后该行验证是否(!(set).add(e))
此代码将打印apple作为输出,因为它是重复值.
问题3:我怎样才能打印出非重复值,只有Orange和Milk而不是Apple?我试过这种方法,但它仍然打印Apple.
List unique = new ArrayList(new HashSet(l1));
在此先感谢您的时间.