java使用hashset_JAVA的HashSet的使用

public class TestSet {

public static void main(String[] args) {

Set set = new HashSet();

Teacher t1 = new Teacher("haitao",50);

Teacher t2 = new Teacher("xubin",1000);

Teacher t3 = new Teacher("wangwei",80000);

Teacher t4 = new Teacher("haitao",50);

set.add(t1);

set.add(t2);

set.add(t3);

set.add(t4);

Set treeset = new TreeSet(set);

treeset.addAll(set);

//  t4.setName("hai"); 导致内存泄露

//  set.remove(t4);

Iterator it = set.iterator();

while(it.hasNext()){

System.out.println(it.next());

}

}

}

public class Teacher implements Comparable{//Comparable接口用于排序

private String name;

private int salary;

public Teacher(String name, int salary) {

this.name = name;

this.salary = salary;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getSalary() {

return salary;

}

public void setSalary(int salary) {

this.salary = salary;

}

@Override

public String toString() {

return this.name+":"+this.salary;

}

public int compareTo(Object o) {

if(o instanceof Teacher){

Teacher teacher = (Teacher)o;

//return this.getSalary()-teacher.getSalary();

return this.getName().compareTo(teacher.getName());

}

return 0;

}

@Override

public boolean equals(Object obj) {

//System.out.println("in equals...");

if(this == obj){

return true;

}

if(obj == null){

return false;

}

if(obj instanceof Teacher){

Teacher t1 = (Teacher) obj;

return t1.getName().equals(this.getName());

}

return false;

}

public int hashCode() {

//System.out.println("in hashCode...");

return name.hashCode();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值