java----泛型
自定义泛型:
泛型只会在编译器存在,在运行期,会被擦除
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。public class Demo { public static void main(String[] args){ Node<String> str = new Node<String>("ddd"); Node<Integer> num = new Node<>(10); System.out.println(str); System.out.println(num); } } class Node<T>{ private T Date; private Node(){}; public Node(T Data){ this.Date = Data; } public T getDate() { return Date; } public void setDate(T date) { Date = date; } @Override public String toString() { return "Node{" + "Date=" + Date + '}'; } }
基本使用
import java.util.*; public class Demo { public static void main(String[] args){ Node<Number> num1 = new Node<Number>(20); Node<Integer> num2 = new Node<>(10); //Node.getData(num1); //不支持,不能进行转换 Node.getData(num2); Node.getData2(num1); //使用了通配符,既可 //此时泛型可以是Number包扩他的所有的子类 Node<Short> num3 = new Node<Short>((short) 11); Node.getData3(num1); Node.getData3(num3); //此时泛型可以是Byts包扩他的所有的父类 Node<Short> num4 = new Node<Short>((short) 11); Node.getData3(num1); Node.getData3(num4); //泛型方法定义 String arr[] = {"1","2","3"}; //好像不能传入一个集合 System.out.println(Arrays.toString(Node.fun(arr,1,2))); //泛型嵌套 Map<Integer,String> map = new HashMap<>(); map.put(1,"k"); map.put(2,"v"); map.put(3,"c"); Set<Map.Entry<Integer, String>> entries = map.entrySet(); for (Map.Entry entry:entries){ System.out.println(entry); } } } class Node<T>{ private T Date; private Node(){}; public Node(T Data){ this.Date = Data; } public T getDate() { return Date; } public void setDate(T date) { Date = date; } @Override public String toString() { return "Node{" + "Date=" + Date + '}'; } public static void getData(Node<Integer> node){ System.out.println(node.getDate()); } //使用通配符定义泛型类型,只能输出,不能修改 public static void getData2(Node<?> node){ //node.setDate(20); //报错 System.out.println(node.getDate()); } //设置上限,同样不能设置 public static void getData3(Node<? extends Number> node){ //node.setDate(20); //报错 System.out.println(node.getDate()); } //设置下限,包扩Byte,以及所有的父类 public static void getData4(Node<? super Byte> node){ //node.setDate(20); //报错 System.out.println(node.getDate()); } public static <T> T[] fun(T[] array,int i1,int i2){ T temp = array[i1]; array[i1] = array[i2]; array[i2] = temp; return array; } }

更多精彩