Java

来源:互联网 发布:模拟人生2数据丢失 编辑:程序博客网 时间:2024/06/09 18:39

  • Stack and Queue
  • PriorityQueue
  • HashSet and HashMap
  • TreeSet and TreeMap


package Other;public class Person implements Comparable<Person>{private String name;private Integer age;public Person() {}public Person(String name, Integer age) {this.name = name;this.age = age;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + ((age == null) ? 0 : age.hashCode());result = prime * result + ((name == null) ? 0 : name.hashCode());        return result;}@Overridepublic boolean equals(Object obj) { if (this == obj)            return true;        if (obj == null)            return false;        /*         * .getClass().getName() -> Dog         * .class.getName() -> Animal         */        if(getClass() != obj.getClass())            return false;        Person other = (Person)obj;                if(age == null){            if (other.age != null)                return false;        }else if(!age.equals(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 Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}@Overridepublic int compareTo(Person o) {int ans = this.age - o.age;if (ans == 0) return this.name.compareTo(o.name);else return ans;}}


package Other;import java.util.TreeSet;/* * 使用 TreeSet 的对象要实现三个接口: * 1. hashCode() * cause:TreeSet 依靠 TreeMap,TreeMap 依赖HashTable * 2. equals() * cause:比较对象是否相同 * 3. compareTo() - Comparable<Person> * cause:排序 */public class _30_ {public static void main(String[] args) {TreeSet<Person> set = new TreeSet<Person>();set.add(new Person("xiaoming", 21));set.add(new Person("xiaohong", 23));set.add(new Person("xiaohong", 21));System.out.println(set.first().getName() + "/" + set.last().getName());System.out.println(set.first().getAge() + "/" + set.last().getAge());}}

xiaohong/xiaohong21/23


原创粉丝点击