删除arraylist中的重复项 [英] Remove duplicate items in arraylist
本文介绍了删除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);
}
}
推荐答案
你不能使用sort
方法,要求不允许它。
另一方面,你可以使用代替
语句:两个嵌套循环可以执行诀窍。
<小> [更新]
你必须仔细阅读文档 [ ^ ]:'删除此列表中指定位置的元素。将任何后续元素向左移位(从索引中减去一个)。'
因此,在删除项目后,您必须处理新索引。
此外:
- 外部循环应停在
(size() - 1)
。- 内循环应该从
(i + 1)
开始。
You cannot use thesort
method, the requirements don't allow it.
On the other hand you may use thefor
statement: two nested loops would do the trick.
[Update]
You have to carefully read the documentation[^]: 'Removes the element at the specified position in this list. Shifts any subsequent elements to the left (subtracts one from their indices).'
So, after a item removal, you have to deal with the new indices.
Moreover:
- The outer loop should stop at
(size()-1)
.- The inner loop should start at
(i+1)
.
// ...
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中的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文