简体   繁体   English

删除LinkedList中的重复项

[英]remove duplicates in LinkedList

I am a beginner in java. 我是Java的初学者。 I have written the following code to find duplicates and remove them in a LinkedList but I am getting a ArrayIndexOutOfBounds Exception. 我已经编写了以下代码来查找重复项并将其删除到LinkedList中,但是我遇到了ArrayIndexOutOfBounds异常。 please help. 请帮忙。 Thanks in advance. 提前致谢。

    import java.util.*;
    public class LinkedListEx 
{
    public static void main(String[] args)
    {
        LinkedList<Integer> l1 = new LinkedList<Integer>();
        l1.add(1);
        l1.add(2);
        l1.add(1);
        l1.add(4);
        l1.add(1);
        System.out.println(l1);
        int i = l1.size();
        for(int j=0;j<i;j++)
        {
            for(int k=j+1;k<i;k++)
            {
                if(l1.get(j) == l1.get(k)){
                    l1.remove(k);
                }
            }
        }
    }
 }

Don't use get(int) on a LinkedList . 不要在LinkedList上使用get(int) It's fine on an ArrayList , but a LinkedList has to traverse the list to find the n'th element. ArrayList上很好,但是LinkedList必须遍历列表以找到第n个元素。

Use a Set to remember which values have already been seen, and iterate the list using an Iterator . 使用Set记住已经看到的值,然后使用Iterator迭代列表。

LinkedList<Integer> l1 = new LinkedList<Integer>();
l1.add(1);
l1.add(2);
l1.add(1);
l1.add(4);
l1.add(1);
System.out.println(l1);

HashSet<Integer> set = new HashSet<Integer>();
for (Iterator<Integer> iter = l1.iterator(); iter.hasNext(); ) {
    Integer value = iter.next();
    if (! set.add(value))
        iter.remove();
}
System.out.println(l1);

Output 输出量

[1, 2, 1, 4, 1]
[1, 2, 4]

Use Iterator to traverse through list when you are going to modify the list. 当您要修改列表时,请使用Iterator遍历列表。

You are removing the items from list, which reduces the size of list but your loop still runs for initial size of list. 您正在从列表中删除项目,这减小了列表的大小,但是循环仍以列表的初始大小运行。

Try: 尝试:

List<Integer> list = new LinkedList<>();
...

Set<Integer> set = new LinkedHashSet<>(list);
// either
list = new LinkedList<>(set);

// or
list.clear();
list.addAll(set);

With Java SE 8 you could also use: 使用Java SE 8,您还可以使用:

list = list.stream().distinct().collect(Collectors.toCollection(LinkedList::new));

Or if it doesn't have to be a LinkedList (not very often needed in my experience): 或者,如果不必一定是LinkedList(根据我的经验,它并不是经常需要的):

list = list.stream().distinct().collect(Collectors.toList());

Your for loop should be more like this and also by updating your variable i : 您的for loop应更像这样,并通过更新变量i

int i = l1.size();
for(int j=0;j<i-1;j++) {
       for(int k=j+1;k<i;k++) {
           if(l1.get(j) == l1.get(k)) {
               l1.remove(k);
               i--; //Updated size
           }
       }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM