java generics wildcards

Today, the original code is looking ArrayList to see such a sign, so strange.
? A wildcard, which means are matched E represents E or subclass specific type is unknown.

1. defining wildcards

Write a similar dynamic data ArrayList

public class Gys<T> {
    private final  static int default_capacity =10;
    private int endIndex =0;
    private Object[] elemts;

    public Gys() {
        this.elemts = new Object[default_capacity];
    }

    public void add(T t){
        if(elemts.length-1< endIndex){
            int newCapcti= default_capacity *2;
            elemts= Arrays.copyOf(elemts,newCapcti);
        }
        elemts[endIndex++]=t;
    }

    public void addAll(Gys<T> cs){
       for(int i=0;i<cs.size();i++){
           add(cs.get(i));
        }
    }

    public int size(){
        return endIndex;
    }

    public T get(int i){
        if(i< endIndex){
            return (T) elemts[i];
        }
        throw new RuntimeException("索引超出界限");
    }


    public static voidmain (String [] args) {
        Gys <number> = thrill New Gys <> (); 
        gys.add ( 25 ); 
        Gys <Integer> = gys2 New Gys <> (); 
        gys2.add ( 2 ); 
        gys.addAll (gys2); 
    } 
}

 

 

 

 

Modify the above code, into the following parameters addAll

 public void addAll(Gys<? extend T> cs){
       for(int i=0;i<cs.size();i++){
           add(cs.get(i));
        }
}

This time code is compiled through. And can normally access its elements.

 

2. indefinite wildcards.

Rewrite addAll method code.

 

 public void addAll(Gys<?> cs){
       for(int i=0;i<cs.size();i++){
           add(cs.get(i));
        }
    }

 

The above code compiler is not passed. ? It indicates the type of uncertainty, from a security point of view indefinite generic and can not write.
But this use.

/**
     *判断元素是否存在
     */
    public boolean isHas(Gys<?> gys,Object elemt){
       for(int i=0;i<gys.size();i++){
           if(gys.get(i).equals(elemt)){
               return  true;
           }
       }
       return false;
   }

   In addition to <extend E?> Usage; there <? Super E> usage, it indicates the type of the parent class E or E's. However introduce more with less.

 

Guess you like

Origin www.cnblogs.com/guoyansi19900907/p/12142234.html