1. 泛型概述
- Java泛型是JDK1.5中引入的一个新特性,其本质是参数化类型,把类型作为参数传递
- 常见形式有泛型类、泛型接口、泛型方法
- 语法:
- 好处:
- 提高代码的重用性
- 防止类型转换异常,提高代码的安全性
2. 泛型类
public class Test {
public static void main(String[] args) {
TestGenericClass<String> testGeneric1 = new TestGenericClass<String>();
testGeneric1.t = "ABC";
testGeneric1.show("abc");
System.out.println(testGeneric1.getT());
TestGenericClass<Integer> testGeneric2 = new TestGenericClass<>();
testGeneric2.t = 10;
testGeneric2.show(100);
System.out.println(testGeneric2.getT());
}
}
public class TestGenericClass<T> {
T t;
public void show(T t) {
System.out.println(t);
}
public T getT() {
return t;
}
}
3. 泛型接口
public class Test {
public static void main(String[] args) {
TestInterface1 testInterface1 = new TestInterface1();
System.out.println(testInterface1.server("abc"));
TestGenericInterface<String> testGeneric = new TestInterface1();
System.out.println(testGeneric.server("qwe"));
TestInterface2<Integer> testInterface2 = new TestInterface2<>();
System.out.println(testInterface2.server(999));
}
}
public class TestInterface1 implements TestGenericInterface<String> {
@Override
public String server(String s) {
System.out.println(s);
return s + "123";
}
}
public class TestInterface2<T> implements TestGenericInterface<T> {
@Override
public T server(T t) {
System.out.println(t);
return t;
}
}
public interface TestGenericInterface<T> {
String name = "ABC";
T server(T t);
}
4. 泛型方法
public class Test {
public static void main(String[] args) {
TestGenericMethod testGenericMethod = new TestGenericMethod();
testGenericMethod.show("ABC");
testGenericMethod.show(123);
}
}
public class TestGenericMethod {
public <T> T show(T t) {
System.out.println("ABC" + t);
return t;
}
}
5. 泛型集合
- 概念:参数化类型、类型安全的集合,强制集合元素的类型必须一致
- 特点:
- 编译时即可检查,而非运行时抛出异常
- 访问时,不必类型转换(拆箱)
- 不同泛型之间引用不能相互赋值,泛型不存在多态
import java.util.ArrayList;
import java.util.Iterator;
public class Test {
public static void main(String[] args) {
ArrayList<String> arrayList1 = new ArrayList<>();
arrayList1.add("ABC");
arrayList1.add("abc");
for (String str : arrayList1) {
System.out.println(str);
}
ArrayList<Student> arrayList2 = new ArrayList<>();
Student student1 = new Student("A", 10);
Student student2 = new Student("B", 20);
Student student3 = new Student("C", 30);
arrayList2.add(student1);
arrayList2.add(student2);
arrayList2.add(student3);
Iterator<Student> iterator = arrayList2.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
class Student {
String name;
int age;
Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}