Java之泛型练习
package cn.itcast.generics;import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;/** 方法一:實現Comparable接口*/
//class Person implements Comparable<Person> {//實現Comparable接口,使得集合元素具備可比較性
// String name;
// int age;
//
// public Person(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;
// }
//
// @Override
// public int compareTo(Person p) {//復寫Comparable的compareTo()方法
Person p = (Person) o;
// /*
// * 按年齡進行比較
// */
int temp=this.age-p.age;
return temp==0?this.getName().compareTo(p.getName()):temp;
// /*
// * 按姓名進行比較
// */
// int temp=this.getName().compareTo(p.getName());
// return temp==0?this.age-p.age:temp;
// }
//
//}
/** 方法2:實現Comparator接口,覆蓋compare()方法,* 并且將該類對象作為實際參數傳遞給TreeSet集合的構造函數*/
class Person implements Comparator<Person>{String name;int age;public Person() {}public Person(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;}@Overridepublic int compare(Person o1, Person o2) {int temp=o1.getName().compareTo(o2.getName());return temp==0?o1.getAge()-o2.getAge():temp;}
}public class GenericDemo2 {/*** @param args*/public static void main(String[] args) {TreeSet<Person> p = new TreeSet<Person>(new Person());p.add(new Person("lisi", 21));p.add(new Person("ahangsan", 42));p.add(new Person("wangwu", 21));p.add(new Person("buliu", 34));p.add(new Person("xuliu", 26));Iterator<Person> it = p.iterator();while (it.hasNext()) {Person p2 = it.next();System.out.println(p2.getName() + ":::" + p2.getAge());}}}
?
轉載于:https://www.cnblogs.com/ysw-go/p/5270272.html
總結
- 上一篇: 通过100个单词掌握英语语法(三)am/
- 下一篇: java美元兑换,(Java实现) 美元