HashSet的重写comparbleble和compartor比较方法

//先创建一个类

package com.test;
/**字显示在博客首页作为文章摘要
 * 猫类
 */
import java.util.Comparator;


public class Cat implements Comparable,Comparator{
String name;
int age;
//提供全参构造方法
public Cat(String name, int age) {
super();
this.name = name;
this.age = age;
}
//重写hashCode和equals方法
@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;
}


@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Cat other = (Cat) 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;
}

//重写Comparator自定义比较方法
@Override
public int compare(Cat o1, Cat o2) {
if(o1.name.length()>o2.name.length()){
return 1;
}
if(o1.name.length()return -1;
}
if(o1.name.length()==o2.name.length()){
return o1.compareTo(o2);
}
return 0;
}

//重写Comparable自定义比较方法
@Override
public int compareTo(Cat o) {
if(this.name.hashCode()>o.name.hashCode()){
return 1;
}
if(this.name.hashCode()return -1;
}
if(this.name.hashCode()==o.name.hashCode()&&this.age==o.age){
return 0;
}
return 1;
}



}



//创建一个测试类

package com.test;



import java.util.HashSet;


public class Test{
public static void main(String[] args) {
HashSet hs= new HashSet();
hs.add(new Cat("小黑", 6));
hs.add(new Cat("小白", 5));
hs.add(new Cat("小橘", 4));
hs.add(new Cat("小花", 3));
for(Cat c:hs){
System.out.println(c.name+"    "+c.age);
}
}

}





你可能感兴趣的:(HashSet的重写comparbleble和compartor比较方法)