• TreeSet中的排序问题——Comparable


    package com.etc.hashset;
    
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Set;
    import java.util.TreeSet;
    
    public class TestHashSet {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    
    		Set set=new TreeSet();
    		set.add(new Student("zhangsan",20));
    		set.add(new Student("zhangsan",20));
    		set.add(new Student("zhangsan5",29));
    		set.add(new Student("zhangsan3",25));
    		set.add(new Student("zhangsan7",27));
    		set.add(new Student("zhangsan1",21));
    
    	    Iterator it = set.iterator();
    	    int num=0;
    	    while(it.hasNext()){ 
    	    	System.out.println(num+++"-"+it.next()); 
    	    }
    	}
    }
    /**
    * Comparable是专门用来对TreeSet和TreeMap进行排序用的,comparable是自然排序,所以在对象所在的类实现该接口即可,TreeSet就不需要再指定专门的构造器
    *
    */
    class Student implements Comparable { @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; Student other = (Student) 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 Student() { } public Student(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; } String name; int age; @Override public int compareTo(Object o) { if(o instanceof Student){ Student stu=(Student)o; return this.age-stu.age; } return 0; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + "]"; } }

      

  • 相关阅读:
    CSS知识总结一
    Html知识总结一
    转:B/S和C/S结构的区别
    转:理解本真的 REST 架构风格
    转载:简洁明了说明RESTful架构是什么
    名词理解
    转: 如何理解API,API 是如何工作的
    WEB的理解
    开关按钮的实现
    ssm学习之ssm框架详解
  • 原文地址:https://www.cnblogs.com/1020182600HENG/p/6722761.html
Copyright © 2020-2023  润新知