# Set集合重复元素的判断

Set集合比较特殊,他的方法基本上和Collection接口的方法一致,并且他没有根据索引得到对应值的get(int index)方法. 更重要的是Set集合不能放置重复的元素.她是怎么判断的呢?那么,我们首先要让对象具有比较性

public static void main(String[] args) {
testTreeSet();
}

private static void testTreeSet() {
TreeSet<Person> treeSet = new TreeSet<Person>();

Iterator<Person> 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<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 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;
}

}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283

Person [name=Tom, age=20]
Person [name=Jim, age=21]
size = 2

public static void main(String[] args) {
testTreeSet();
}

private static void testTreeSet() {
TreeSet<Person> treeSet = new TreeSet<Person>(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
if (o1.getAge() == o2.getAge()) {
return 0;
}

if (o1.getAge() > o2.getAge()) {
return 1;
}

return -1;
}
});

Iterator<Person> 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 + "]";
}
}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263

Person [name=Tom, age=20]
Person [name=Jim, age=21]
size = 2