集合框架-泛型在集合中的應用
阿新 • • 發佈:2021-10-24
1 package cn.itcast.p1.generic.demo; 2 3 import java.util.Iterator; 4 import java.util.TreeSet; 5 6 import cn.itcast.p2.bean.Person; 7 import cn.itcast.p3.comparator.ComparatorByName; 8 9 public class GenericDemo2 { 10 11 public static void main(String[] args) { 12 // TODO Auto-generated method stubView Code13 TreeSet<Person> ts = new TreeSet<Person>(new ComparatorByName()); 14 ts.add(new Person("lisi8",21)); 15 ts.add(new Person("lisi3",23)); 16 ts.add(new Person("lisi",21)); 17 ts.add(new Person("lis0",20)); 18 19 20 Iterator<Person> it = ts.iterator();21 22 while(it.hasNext()) { 23 Person p = it.next(); 24 System.out.println(p.getName()+":"+p.getAge()); 25 } 26 } 27 28 }
1 package cn.itcast.p2.bean; 2 3 import java.util.Comparator; 4 5 public class Person implements Comparable<Person>{Person6 private String name; 7 private int age; 8 9 10 public Person() { 11 super(); 12 // TODO Auto-generated constructor stub 13 } 14 15 public Person(String name, int age) { 16 super(); 17 this.name = name; 18 this.age = age; 19 } 20 public int compareTo(Person p) {//指定比較型別,傳入比較型別 21 // Person p= (Person)obj; 22 int temp = this.age-p.age; 23 return temp==0?this.name.compareTo(p.name):temp; 24 } 25 26 27 // @Override 28 // public boolean equals(Object obj) {//不能把Object改為Person,equals方法來自Object,Object沒有定義泛型 29 // // TODO Auto-generated method stub 30 // if (this == obj) { 31 // return true; 32 // } 33 // if (!(obj instanceof Person)) { 34 // throw new RuntimeException() 35 // } 36 // Person p = (Person)obj; 37 // return super.equals(obj); 38 // } 39 /* 40 * @Override public int hashCode() { final int prime = 31; int result = 1; 41 * result = prime * result + age; result = prime * result + ((name == null) ? 0 42 * : name.hashCode()); return result; } 43 * 44 * @Override public boolean equals(Object obj) { if (this == obj) return true; 45 * if (obj == null) return false; if (getClass() != obj.getClass()) return 46 * false; Person other = (Person) obj; if (age != other.age) return false; if 47 * (name == null) { if (other.name != null) return false; } else if 48 * (!name.equals(other.name)) return false; return true; }//alt+shift+s 49 * hashCode和equals 50 */ 51 public String getName() { 52 return name; 53 } 54 public void setName(String name) { 55 this.name = name; 56 } 57 public int getAge() { 58 return age; 59 } 60 public void setAge(int age) { 61 this.age = age; 62 } 63 64 }
1 package cn.itcast.p3.comparator; 2 3 import java.util.Comparator; 4 5 import cn.itcast.p2.bean.Person; 6 7 public class ComparatorByName implements Comparator<Person> {//ctrl+1快速實現方法 8 9 @Override 10 public int compare(Person o1, Person o2) { 11 // TODO Auto-generated method stub 12 int temp = o1.getName().compareTo(o2.getName()); 13 return temp==0?o1.getAge()-o2.getAge():temp; 14 } 15 16 }ComparatorByName