Sortable Java collection without duplicates

跟風遠走 提交于 2019-12-10 10:59:07

问题


I am searching for sortable (I mean sorting after initialization and many times using Comparator) Java class collection without duplicates. Is there any more pure solution than writing code which will opaque and prevent for example some ArrayList for adding another object with the same value that already exists?

Edit 1: I should add some explanation about sorting. I need to sort this set of values many times with different comparators (diversity of implementations).


回答1:


Use a Set! The common implementations are HashSet and TreeSet. The latter preserves the order of items as it implements SortedSet.




回答2:


Set Interface---->SortedSet Interface----->TreeSet Class
Set Interface---->HashSet Class
Set Interface---->LinkedHashSet Class

You can Use TreeSet. It will remove duplicates.

TreeSet implements SortedSet Interface so that it will sort the elements entered

        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);

Output

[1, 6, 12, 47, 56]



回答3:


Use Set for unique elements.. You can always use Collections.sort() to sort any collection you use




回答4:


This is a set.

usage:

Collection collection = new HashSet();



回答5:


It might be best to extend a standard collection or implement one from scratch. Eg:

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(..) {..}
}

And then you've got Collections.sort as previously stated. I would want to double-check everything though -- I can just imagine library methods making false assumptions about SetList because it extends ArrayList, leading to disaster. Read the javadocs of ArrayList, List, and Collection for a start, and really consider doing one from scratch.



来源:https://stackoverflow.com/questions/14887976/sortable-java-collection-without-duplicates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!