代码链接:https://download.csdn.net/download/qq_52354698/86401487?spm=1001.2014.3001.5501
class Person<E> {
E s;
public Person(E s){
this.s = s;
}
public E f() {
return s;
}
}
interface 接口 <T> {} 和 class 类 <K,V> p {}
说明:
要在类名后面指定类型参数的值(类型)。
List<String> strList = new ArrayList<String>();
Interor<Customer> iterator = customers.iterator();
package com.qdu.generic;
import java.util.*;
/**
* @author dell
* @version 1.0
*/
public class GenericExercise {
public static void main(String[] args) {
HashSet<Student> hashSet = new HashSet<Student>();
hashSet.add(new Student("jack", 18));
hashSet.add(new Student("king", 28));
for (Student o : hashSet) {
System.out.println(o.getName() + " " + o.getAge());
}
HashMap<String, Student> hashMap = new HashMap<String, Student>();
hashMap.put("tom", new Student("tom", 18));
hashMap.put("sam", new Student("sam", 38));
Set<Map.Entry<String, Student>> entries = hashMap.entrySet();
Iterator<Map.Entry<String, Student>> iterator = entries.iterator();
while (iterator.hasNext()) {
Map.Entry<String, Student> next = iterator.next();
System.out.println(next.getKey() + " " + next.getValue());
}
}
}
class Student {
private String name;
private int age;
public Student(String name, int age) {
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;
}
}
interface List{},public class HashSet{}
说明:T、E只能是引用类型
在给泛型指定具体类型后,可以传入该类型或者其子类类型
class 类名<T, R...>{
成员
}
interface 接口名<T, R...>{
}
修饰符 <T, R...> 返回类型 方法名(参数列表){
}
泛型不具备继承性
