我对hashsets并不是很好,我想知道我是否能够使用.addAll方法检索hashets删除的重复项.所以在我的代码中,它要求用户输入最多20的值,如果它是-1,则中断.然后删除重复项并显示完成的列表.但现在我想显示已删除重复项的列表列表.例如:2 = 3个重复5 = 5个重复.这是我的代码:
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.Scanner;
import java.util.Set;
public class Question {
public static void main(String[] args) {
ArrayList<Integer> entries = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
int counter = 0;
int sentinel = -1;
while (entries.size() <= 20) {
System.out.println("Please enter some numbers into the entries list");
entries.add(input.nextInt());
if (entries.get(counter) == sentinel) {
entries.remove(counter);
break;
}
System.out.println("You've added: " + entries.get(counter) + ". So far your list is as shows: " + entries);
counter++;
}
System.out.println("The list is: " + entries);
System.out.println("Checking for Duplicates...");
Set<Integer> num = new LinkedHashSet<>(entries);
num.addAll(entries); // The addAll method deletes duplicates
System.out.println(num);
entries.clear();
entries.addAll(num);
System.out.println("The Finished list is: " + entries);
}
}
解决方法:
不幸的是,Set不会跟踪它拒绝的所有项目.您必须手动执行此操作.快速而肮脏的方法如下:
Set<Integer> noDuplicates = new LinkedHashSet<Integer>();
List<Integer> rejects = new ArrayList<Integer>();
for(Integer entry : entry) {
if(!noDuplicates.add(entry)) { rejects.add(entry) }
}
请注意,当尝试将重复元素添加到Set时,add方法返回false并拒绝添加请求.