标签:vat col person rip java数据类型 type bsp arraylist 运行
import java.util.ArrayList; import java.util.List; public class ProblemTest { public static void main(String[] args) { List persons = new ArrayList(); persons.add("李一桐"); persons.add("刘亦菲"); persons.add("鞠婧祎"); //不小心加入了一个int类型的数据 persons.add(10); persons.forEach(person -> System.out.println(((String) person).length())); } }
Set<String> persons = new HashSet<>(); Map<String, Integer> persons = new HashMap<>();
我们就是在类名的后面加上类型的替代符,比如上面的T,K,V。我们在使用的时候,就直接把这些T,K,V替换成对应的类型名称就好了。
/** * @ClassName MyDefineClassInitTypeExample * @projectName: object1 * @author: Zhangmingda * @description: 自定义泛型测试 * date: 2021/4/11. */ public class MyDefineClassInitTypeExample { private static class Student<T>{ private T type; public Student(T type) { this.type = type; } public T getType() { return type; } } public static void main(String[] args) { Student<String> student = new Student<>("高中"); System.out.println(student.getType());//高中 Student<Integer> student1 = new Student<>(202101); System.out.println(student1.getType());//202101 } }
private static class ElementaryStudent extends Student<T>{ public ElementaryStudent(T type){ super(type); } }
public class MyDefineClassInitTypeExample { private static class Student<T>{ private T type; public Student(T type) { this.type = type; } public T getType() { return type; } } private static class ElementaryStudent extends Student<String>{ public ElementaryStudent(String type){ super(type); } } public static void main(String[] args) { ElementaryStudent elementaryStudent = new ElementaryStudent("小学"); System.out.println(elementaryStudent.getType()); //小学 } }
/** * @ClassName MyDefineClassInitTypeExample * @projectName: object1 * @author: Zhangmingda * @description: 自定义泛型测试 * date: 2021/4/11. */ public class MyDefineClassInitTypeExample { private static class Student<T>{ private T type; public Student(T type) { this.type = type; } public T getType() { return type; } } private static class ElementaryStudent<T> extends Student<T>{ public ElementaryStudent(T type){ super(type); } } public static void main(String[] args) { ElementaryStudent<Integer> elementaryStudent1 = new ElementaryStudent<>(202107); System.out.println(elementaryStudent1.getType()); } }
ElementaryStudent<Integer> elementaryStudent1 = new ElementaryStudent<>(202107); System.out.println(elementaryStudent1.getType()); ElementaryStudent<String> elementaryStudent2 = new ElementaryStudent<>("幼儿园"); System.out.println(elementaryStudent2.getType()); System.out.println(elementaryStudent1.getClass()); //class MyDefineClassInitTypeExample$ElementaryStudent System.out.println(elementaryStudent2.getClass()); //class MyDefineClassInitTypeExample$ElementaryStudent System.out.println(elementaryStudent.getClass().equals(elementaryStudent2.getClass()));//true
java数据类型:集合存储元素类型限制<泛型> ;自定义泛型<T>;派生子类泛型<T> super(泛型内参数)
标签:vat col person rip java数据类型 type bsp arraylist 运行
原文地址:https://www.cnblogs.com/zhangmingda/p/14643453.html