- public class Students implements Comparable<Students> {
- private String name;
- private int age;
- public Students() {
- super();
- }
- public Students(String name, int age) {
- super();
- this.name = name;
- this.age = age;
- }
- @Override
- public int compareTo(Students o) {
- System.out.println("compareTo");
- return this.name.compareTo(o.getName());
- }
- @Override
- public int hashCode() {
- System.out.println("zhixing");
- 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) {
- System.out.println("zhixing");
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- Students other = (Students) 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;
- }
- 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;
- }
- public static void main(String[] args) {
- Set<Students> treeSet = new TreeSet<Students>();
- treeSet.add(new Students("xiaoqiang", 32));
- treeSet.add(new Students("xiaoqiang", 32));
- treeSet.add(new Students("xiao", 22));
- }
- }
复制代码 打印结果就只有两个compareTo。。。没有看到equals和hashCode方法的输出语句; |