Set collection
Disorder, no subscripts, elements of the collection will not be repeated.
HashSet
Print result to heavy and chaotic.
example
public static void main(String[] args) {
HashSet<Person> hs = new HashSet<Person>(); //定义了一个Person类
hs.add(new Person("张三",23));
hs.add(new Person("张三",23));
hs.add(new Person("李四",24));
hs.add(new Person("李四",24));
hs.add(new Person("李四",24));
hs.add(new Person("李四",24));
System.out.println(hs.size());
}
When the print target is not automatically de-emphasis, and to rewrite equals hashcode method, the method further rewriting rewriting Person class.
LinkedHashSet
It can be understood as ordered HashSet
How to store on how to print.
Example: LinkedHashSet removed using Arraylist repeating elements.
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("a");
list.add("b");
list.add("b");
list.add("b");
getSingle(list);
System.out.println(list);
}
private static void getSingle(List<String> list) {
// TODO Auto-generated method stub
LinkedHashSet<String> llist = new LinkedHashSet<String>();
/*
* for (String string : list) { llist.add(string); }
*/
llist.addAll(list);
list.clear();
list.addAll(llist);
}
Treeset
Treeset used to sort.
Create a Treeset, while ordering the removal of repeating elements.
private static void demo1() {
TreeSet<Integer> ts = new TreeSet<Integer>();
ts.add(1);
ts.add(3);
ts.add(3);
ts.add(3);
ts.add(2);
ts.add(3);
ts.add(3);
ts.add(3);
ts.add(3);
ts.add(3);
System.out.println(ts);
}
When comparing objects
private static void demo2() {
TreeSet<Person> ts = new TreeSet<>();
ts.add(new Person("张三", 23));
ts.add(new Person("李四", 24));
ts.add(new Person("王五", 25));
ts.add(new Person("赵六", 26));
ts.add(new Person("张三", 23));
System.out.println(ts);
}
Needs to be rewritten (COMPARATO implemented method comparable interface) the Person class comparator
The following is ComparaTo rewriting method in the Person class (Person class to inherit the Comparable interface.)
public int compareTo(Person o) {
// TODO Auto-generated method stub
int lenth = this.name.length() - o.name.length();//名字长度为主要判断条件
int num = lenth ==0? this.name.compareTo(o.name) : lenth;//年龄为次要条件
return num == 0? this.age - o.age : num;
}
return values to the left of the row of regular alignment object (front), whereas the right row (back), then the zero is the same object, not added Treeset
Another configuration of the comparator
class ComparByLen implements Comparator
@Override
public int compare(String s1, String s2)
{
int num = s1.length() -s2.length();
return num==0? s1.compareTo(s2) : num;
}
private static void demo5() {
TreeSet ts = new TreeSet(new ComparByLen());
ts.add("aaaa");
ts.add("z");
ts.add("wc");
ts.add("nba");
ts.add("aaa");
System.out.println(ts);
}
At this time, incoming configured directly in the newly created class, ComparByLen ();