您的位置:首页 > 编程语言 > Java开发

Java之泛型练习

2016-03-12 22:11 543 查看
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;
}
@Override
public 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());
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: