import java.util.*;
/*
當元素自身不具備比較性,或者具備的比較性不是所需要的。
這時需要讓容器自身具備比較性。
定義了比較子,將比較子對象作為參數傳遞給TreeSet集合的建構函式。
當兩種排序都存在時,以比較子為主。
定義一個類,實現Comparator介面,覆蓋compare方法。
*/
class Student implements Comparable//該介面強制讓學生具備比較性。
{
private String name;
private int age;
Student(String name,int age)
{
this.name = name;
this.age = age;
}
public int compareTo(Object obj)
{
//return 0;
if(!(obj instanceof Student))
throw new RuntimeException("不是學生對象");
Student s = (Student)obj;
//System.out.println(this.name+"....compareto....."+s.name);
if(this.age>s.age)
return 1;
if(this.age==s.age)
{
return this.name.compareTo(s.name);
}
return -1;
/**/
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
class TreeSetDemo2
{
public static void main(String[] args)
{
TreeSet ts = new TreeSet();
ts.add(new Student("lisi02",22));
ts.add(new Student("lisi02",21));
ts.add(new Student("lisi007",20));
ts.add(new Student("lisi09",19));
ts.add(new Student("lisi06",18));
ts.add(new Student("lisi06",18));
ts.add(new Student("lisi007",29));
//ts.add(new Student("lisi007",20));
//ts.add(new Student("lisi01",40));
Iterator it = ts.iterator();
while(it.hasNext())
{
Student stu = (Student)it.next();
System.out.println(stu.getName()+"..."+stu.getAge());
}
}
}
class MyCompare implements Comparator
{
public int compare(Object o1,Object o2)
{
Student s1 = (Student)o1;
Student s2 = (Student)o2;
int num = s1.getName().compareTo(s2.getName());
if(num==0)
{
return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));
/*
if(s1.getAge()>s2.getAge())
return 1;
if(s1.getAge()==s2.getAge())
return 0;
return -1;
*/
}
return num;
}
}
泛型:JDK1.5版本以後出現新特性。用於解決安全問題,是一個型別安全機制。
好處
1.將運行時期出現問題ClassCastException,轉移到了編譯時間期。,
方便於程式員解決問題。讓運行時問題減少,安全。,
2,避免了強制轉換麻煩。
泛型格式:通過<>來定義要操作的引用資料類型。
在使用java提供的對象時,什麼時候寫泛型呢。
通常在集合架構中很常見,
只要見到<>就要定義泛型。
其實< > 就是用來接收類型的。
當使用集合時,將集合中要儲存的資料類型作為參數傳遞到< >中即可
? 萬用字元。也可以理解為預留位置。
泛型的限定;
。 extends E:可以接收E類型或者E的子類型。上限。
。 super E:可以接收E類型或者E的父類型。下限