本文介绍了删除arraylist中的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下问题

I have below question

Quote:

您将获得以下数字序列,

1,652,5,15,385,4,55,666,13,2,4658,9,55,588,10,1083,17,4。

你可以通过使用For循环和ArrayList删除重复的数字。

You are given the following sequence of numbers,
1, 652 ,5, 15, 385, 4 , 55, 666, 13, 2, 4658, 9, 55, -588, 10, 1083, 17 ,4.
You can remove the duplicate numbers by only using For loop and ArrayList .



这是我的输出


And this is my output

Before remove : [-588, 1, 2, 4, 4, 5, 9, 10, 13, 15, 17, 55, 55, 385, 652, 666, 1083, 4658]
[-588, 2, 4, 9, 13, 17, 55, 652, 1083]

有些商品已被删除。



编辑

删除排序方法后,我的输出如下

Some items are removed.

Edit
After I remove the sort method, my output as below

Before remove : [1, 652, 5, 15, 385, 4, 55, 666, 13, 2, 4658, 9, 55, -588, 10, 1083, 17, 4]
[1, 5, 385, 55, 13, 4658, -588, 1083, 4]





我的尝试:





What I have tried:

public class Ex {
    public static void main(String[] args) {

        ArrayList list = new ArrayList();
        list.add(1);
        list.add(652);
        list.add(5);
        list.add(15);
        list.add(385);
        list.add(4);
        list.add(55);
        list.add(666);
        list.add(13);
        list.add(2);
        list.add(4658);
        list.add(9);
        list.add(55);
        list.add(-588);
        list.add(10);
        list.add(1083);
        list.add(17);
        list.add(4);

        Collections.sort(list);

        System.out.println("Before remove : " + list);

        for (int i = 0; i < list.size(); i++) {
            for (int j = 1; j < list.size(); j++) {
                if (list.get(i) == list.get(j)) {
                    list.remove(j);
                }
            }
        }
        System.out.println(list);
    }
}

推荐答案

// ...

System.out.println("Before remove : " + list);

for (int i = 0; i < list.size()-1; ++i)
{
    for (int j = i+1; j < list.size(); ++j)
    {
        if (list.get(i) == list.get(j))
        {
            list.remove(j);
            --j; //deal with shifted indices
        }
    }
}
System.out.println(list);

[/ Update]


这篇关于删除arraylist中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:50