package com.wsq.set;
import java.util.TreeSet;
import com.wsq.bean.Person;
public class Demo3_TreeSet {
/**
* TreeSet集合是用来对元素进行排序的,同样它也可以保证元素的唯一
* 当compareTo()方法返回0的时候,只有一个元素
* 当compareTo()方法返回正数的时候,怎么存,就怎么取
* 当compareTo()方法返回负数的时候,集合会倒序存储
* */
public static void main(String[] args) {
}
private static void demo4() {
TreeSet<Person> yy = new TreeSet<>();
yy.add(new Person("zhangshan",23));
yy.add(new Person("lisi",13));
yy.add(new Person("wangwu",33));
yy.add(new Person("zhaoliu",43));
yy.add(new Person("aaaa",53));
System.out.println(yy);
}
private static void demo3() {
TreeSet<Person> wsq = new TreeSet<>();
wsq.add(new Person("李四",13));
wsq.add(new Person("张三",23));
wsq.add(new Person("王五",43));
wsq.add(new Person("赵六",33));
System.out.println('张' + 0);
System.out.println('李' + 0);
System.out.println('王' + 0);
System.out.println('赵' + 0);
System.out.println(wsq);
}
private static void demo2() {
TreeSet<Person> wsq = new TreeSet<>();
/**
* TreeSet底层是一个二叉树:两个叉,小的存储在左边(返回负数),大的存储在右边(返回正数),相等就不存(返回0);
* CompareTo()方法,在TreeSet集合如何存储元素,取决于CompareTo()方法的返回值
*
* 1,第一次返回0,集合中只有一个元素
* 2,第二次返回-1(负数),集合会将存储的元素倒序
* 3,第三次返回1(正数),集合会怎么存。怎么取
* */
wsq.add(new Person("张三",23));
wsq.add(new Person("李四",13));
wsq.add(new Person("周七",13));
wsq.add(new Person("王五",43));
wsq.add(new Person("赵六",33));
System.out.println(wsq);
}
private static void demo1() {
TreeSet<Integer> yy = new TreeSet<>();
yy.add(3);
yy.add(1);
yy.add(1);
yy.add(2);
yy.add(2);
yy.add(3);
yy.add(3);
System.out.println(yy);
}
}
package com.wsq.bean;
public class Person implements Comparable<Person>{
private String name;
private int age;
public Person() {
super();
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public int compareTo(Person o){
int length = this.name.length() - o.name.length();
int num = length == 0 ? this.name.compareTo(o.name) : length;
return num == 0 ? this.age - o.age : num;
}
}