package collection;
import java.util.HashSet;
import java.util.TreeSet;
import java.util.Iterator;
/*
往HashSet集合中存入自定义对象,
姓名和年龄相同为同一对象
*/
public class SetDemo {
/**
* @Set:元素是无序的,元素不可以重复。
*
* Set集合的功能和Connection是一致的
* |--HashSet:底层数据结构是Hash表(一般都有复写hashCode和equals方法) 线程是非同步的
* HashSet是如何保证元素唯一性的呢?
* 是通过元素的两个方法,HashCode 和equals来完成
* 如果元素的HashCode值相同,才会判断equals是否为true;
* 如果元素的HashCode不同,不会调用equals.
*
* 注意:对于判断元素是否存在以及删除等操作,依赖的方法是元素的hashCode和equals方法
*
* |--TreeSet:可以对Set集合中的元素进行排序(按自然顺序)
*
*/
public static void main(String[] args) {
//hash_code();
tree_set();
}
private static void sop(Object obj) {
System.out.println(obj);
}
private static void tree_set() {
//需求,往TreeSet集合中存储自定义对象,学生,想按照学生的年龄进行排序
TreeSet ts = new TreeSet();
ts.add(new Student("lisi02",22));
ts.add(new Student("lisi007",20));
ts.add(new Student("lisi09",19));
ts.add(new Student("lisi08",19));
//ts.add(new Student("lisi01",40));
Iterator it = ts.iterator();
while(it.hasNext()){
Student stu = (Student) it.next();
sop(stu.getName()+"..."+stu.getAge());
}
}
private static void hash_code() {
HashSet hs = new HashSet();
hs.add(new Person1("a1",11));
hs.add(new Person1("a2",12));
hs.add(new Person1("a3",13));
hs.add(new Person1("a2",12));
// hs.add(new Person("a4",14));
sop("a1:"+hs.contains(new Person1("a1",11)));
hs.remove(new Person1("a3",13));
Iterator it = hs.iterator();
while(it.hasNext()){
Person1 p = (Person1)it.next();
sop(p.getName()+"::"+p.getAge());
}
}
}
class Person1{
private String name;
private int age;
Person1(String name,int age){
this.name = name;
this.age = age;
}
public int hashCode(){
//return 60;
System.out.println(name+"......hashCode...."+age);
return name.hashCode()+age;
}
public boolean equals(Object obj){
if(!(obj instanceof Person1)){
return false;
}
Person1 p = (Person1) obj;
System.out.println(this.name+"..equals.."+p.name);
return this.name.equals(p.name) && this.age == p.age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
class Student implements Comparable{
private String name ;
private int age;
Student(String name,int age){
this.name = name;
this.age = age;
}
public int compareTo(Object obj){
if(!(obj instanceof Student)){
throw new RuntimeException("不是学生对象");
}
Student s = (Student) obj;
System.out.println(this.name+"...compareTo.."+s.name);
if(this.age>s.age)
return 1;
if(this.age==s.age){
if(this.name.compareTo(s.name)>0)
return 1;
if(this.name.compareTo(s.name)<0)
return -1;
return 0;
}
else
return -1;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
4462

被折叠的 条评论
为什么被折叠?



