什么是泛型
public class ArrayList<T> {
private T[] array;
private int size;
public void add(T e) {...}
public void remove(int index) {...}
public T get(int index) {...}
}
// T可以是任何class
// 创建可以存储String的ArrayList:
ArrayList<String> strList = new ArrayList<String>();
// 创建可以存储Float的ArrayList:
ArrayList<Float> floatList = new ArrayList<Float>();
// 创建可以存储Person的ArrayList:
ArrayList<Person> personList = new ArrayList<Person>();
// 总结
/*
泛型就是编写模板代码来适应任意类型;
泛型的好处是使用时不必对类型进行强制转换,它通过编译器对类型进行检查;
注意泛型的继承关系:可以把ArrayList<Integer>向上转型为List<Integer>(T不能变!),但不能把ArrayList<Integer>向上转型为ArrayList<Number>(T不能变成父类)。
*/
使用泛型
import java.util.ArrayList;
import java.util.Arrays;
// 使用泛型
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("hello");
list.add("world");
String first = list.get(0);
String second = list.get(1);
System.out.println(first + second);
}
}
public class Main {
public static void main(String[] args) {
ArrayList<Number> list = new ArrayList<>();
list.add(new Integer(123));
list.add(new Double(123.12));
Number first = list.get(0);
Number second = list.get(1);
System.out.println(first);
System.out.println(second);
}
}
// ArrayList<Number> list = new ArrayList<>();后面的<>里面的Number可以省略,会自动识别出Number
// 泛型接口
public class Main{
public static void main(String[] args) {
String[] ss = new String[]{"xiaoshuai","shaoshuai","shuai"};
Arrays.sort(ss);
System.out.println(Arrays.toString(ss));
}
}
// String本身已经实现了Comparable<String>接口,所以可以进行排序
// 换成我们自定义的Person类型就需要写Comparable<Person>接口
public class Main{
public static void main(String[] args) {
Person[] ps = new Person[]{
new Person("shuai",99),
new Person("shaoshuai",88),
new Person("xiaoshuai",77),
};
Arrays.sort(ps);
System.out.println(Arrays.toString(ps));
}
}
class Person implements Comparable<Person>{
String name;
int score;
Person(String name, int score){
this.name = name;
this.score = score;
}
public int compareTo(Person other){
return this.name.compareTo(other.name);
}
public String toString(){
return this.name + "," + this.score;
}
}