How do I remove repeated elements from ArrayList?

后端 未结 30 1715
难免孤独
难免孤独 2020-11-21 06:24

I have an ArrayList, and I want to remove repeated strings from it. How can I do this?

30条回答
  •  悲&欢浪女
    2020-11-21 06:39

    Here's a way that doesn't affect your list ordering:

    ArrayList l1 = new ArrayList();
    ArrayList l2 = new ArrayList();
    
    Iterator iterator = l1.iterator();
    
    while (iterator.hasNext()) {
        YourClass o = (YourClass) iterator.next();
        if(!l2.contains(o)) l2.add(o);
    }
    

    l1 is the original list, and l2 is the list without repeated items (Make sure YourClass has the equals method according to what you want to stand for equality)

提交回复
热议问题