我正在寻找可排序(我的意思是在初始化后排序并多次使用比较器)Java 类集合,没有重复项。有没有比编写不透明的代码更纯粹的解决方案,例如防止某些 ArrayList 添加另一个具有与已存在的值相同的值的对象?
编辑1: 我应该添加一些有关排序的解释。我需要使用不同的比较器(实现的多样性)多次对这组值进行排序。
Set Interface---->SortedSet Interface----->TreeSet Class
Set Interface---->HashSet Class
Set Interface---->LinkedHashSet Class
您可以使用
TreeSet
。它将删除重复项。
TreeSet
实现 SortedSet
接口,以便对输入的元素进行排序
SortedSet s=new TreeSet();
s.add(12);
s.add(12);
s.add(1);
s.add(56);
s.add(6);
s.add(47);
s.add(1);
System.out.println(s);
输出
[1, 6, 12, 47, 56]
使用 Set 来获取唯一元素。您始终可以使用 Collections.sort() 对您使用的任何集合进行排序
class SetList<E> extends ArrayList<E> {
boolean add(E e) {
if (contains(e)) {
return false;
} else {
super.add(e);
return true;
}
}
void add(int index, E e) { .. }
void addAll(..) {..}
void addAll(..) {..}
}
然后你就得到了
Collections.sort
,如前所述。不过,我想仔细检查所有内容——我可以想象库方法对 SetList 做出错误的假设,因为它扩展了 ArrayList,从而导致灾难。首先阅读 ArrayList、List 和 Collection 的 javadoc,并真正考虑从头开始。
public static void main(String[] args) {
// Sample array of names
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
names.add("David");
names.add("Alice"); // Duplicate entry
names.add("Eve");
names.add("Frank");
names.add("Grace");
names.add("Bob"); // Duplicate entry
names.add("Hank");
System.out.println("Original List: " + names);
// Display each duplicate found and the sorted list without the names that are duplicates
}