GENERICS

来源:互联网 发布:淘宝隐形降权怎么解决 编辑:程序博客网 时间:2024/05/02 01:33
 

package genericAndCollection;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class TestGenerics {
 
 static class Fruit{}
 
 static class Apple extends Fruit{}
 
 static class Orange extends Fruit{}
 
 public static void main(String[] args) {
  //1: the difference between ? and T
  //?: means that any number of non-determined class type, it represents N
  //T: means that one non-determined class type, it represents one
  
  //2: generics are not implementing polymorphism 
  List<Fruit> list = new ArrayList<Apple>();
  
  //3:static type or apparent type can not write while using the extends
  //to determine the type edge (downwards)
  List<? extends Fruit> list1 = new ArrayList<Apple>();
  list1.add(null);//otherwise will get compilation error
  //3.1: correct way
  List<Apple> list111 = new ArrayList<Apple>();
  list111.add(new Apple());
  List<? extends Fruit> list11 = list111;
  for(Fruit f: list11){}//to do}--read only
  
  //4: static type or apparent type can not read while using the super
  // to determine the type edge (upwards)
  //here, Gabriel said we can not get(compilation error) is wrong, it can not
  //use get due to no element there
  List<? super Fruit> list2 = new ArrayList<Fruit>();
  list2.get(0);
  //4.1: correct way
  List<Fruit> list22 = new ArrayList<Fruit>();
  list22.add(new Fruit());
  List<? super Fruit> list222 = list22;
  list222.get(0);
  
  //5: the actual type can not use ?, because jvm will have to know which
  //actual type initiated, here ? extends Fruit is any number of type possible
  //edge to Fruit
  List<? extends Fruit> list3 = new ArrayList<? extends Fruit>();
  
  //6: Array with generics, it has been implemented Polymorphism
  Fruit[] fruit = new Apple[5];
  fruit[0] = new Apple();//no error here, because while it runs, javap shows
          //anewarray command in bytecode, it doesn't actually init
                         //the instance of Fruit and Apple, it uses type [Fruit
  
  //7: force to cast while traverse using iterator
  List<Fruit> list7 = new ArrayList<Fruit>();
  //it records the actual types to meta data which located in signature
  //if in method parameter
  list7.add(new Apple());
  list7.add(new Orange());
  Iterator it = list7.iterator();
  while(it.hasNext()){
   System.out.println(it.next());
  }
  //7.1: try this--it shows if no generics here, any type can be added to this list
  //and it won't be forced to cast to Fruit, because it really didn't erase type
  List list77 = new ArrayList();
  list77.add(new Object());
  list77.add(new Orange());
  Iterator it1 = list77.iterator();
  while(it1.hasNext()){
   System.out.println((Apple)it1.next());//please do not froce it to cast
              //will have java.lang.ClassCastException
  }
 }
}

原创粉丝点击