Set集合比较特殊,他的方法基本上和Collection接口的方法一致,并且他没有根据索引得到对应值的get(int index)方法. 更重要的是Set集合不能放置重复的元素.她是怎么判断的呢?那么,我们首先要让对象具有比较性
一,存储的自定义对象实现接口 Comparable
复写public int compareTo()方法. 返回0表示二者相等. 如果返回大于0的整数(一般写1),则认为该对象大于比较的对象.如果返回小于0的整数(一般是-1),则认为该对象小于比较的对象.
下面我们定义一个类Person,如果对象的年龄相等,我们就认为这两个对象相等
public static void main(String[] args) {
testTreeSet();
}
private static void testTreeSet() {
TreeSet treeSet = new TreeSet();
treeSet.add(new Person("Tom", 20));
treeSet.add(new Person("Jim", 21));
treeSet.add(new Person("Jim", 20));
Iterator it = treeSet.iterator();
while (it.hasNext()) {
Person p = it.next();
System.out.println(p.toString());
}
System.out.println("size = "+treeSet.size());
}
static class Person implements Comparable {
private String name;
private int age;
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 int hashCode() {
System.out.println("hashcode " + 17 * age);
return 17 * age;
}
@Override
public boolean equals(Object obj) {
Person p = (Person) obj;
boolean b = (this.age == p.getAge());
if (b) {
System.out.println("一样 " + this.toString() + " "
+ p.toString());
} else {
System.out.println("不一样 " + this.toString() + " "
+ p.toString());
}
return b;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
@Override
public int compareTo(Person o) {
if (this.age == o.getAge()) {
return 0;
}
if (this.age > o.getAge()) {
return 1;
}
return -1;
}
}
运行结果为:
Person [name=Tom, age=20]
Person [name=Jim, age=21]
size = 2
由此分析,在操作treeSet.add(new Person(“Jim”, 20));的时候认为他是一个相同的对象,那么就无法再放入了
二,存储的自定义对象实现接口 Comparable
public static void main(String[] args) {
testTreeSet();
}
private static void testTreeSet() {
TreeSet treeSet = new TreeSet(new Comparator() {
@Override
public int compare(Person o1, Person o2) {
if (o1.getAge() == o2.getAge()) {
return 0;
}
if (o1.getAge() > o2.getAge()) {
return 1;
}
return -1;
}
});
treeSet.add(new Person("Tom", 20));
treeSet.add(new Person("Jim", 21));
treeSet.add(new Person("Jim", 20));
Iterator it = treeSet.iterator();
while (it.hasNext()) {
Person p = it.next();
System.out.println(p.toString());
}
System.out.println("size = "+treeSet.size());
}
static class Person {
private String name;
private int age;
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 + "]";
}
}
结果是:
Person [name=Tom, age=20]
Person [name=Jim, age=21]
size = 2
存入了两个结果.
treeSet.add(new Person(“Jim”, 20)); Jim的年龄和Tom相同被认为是一样的对象