Analysis of common wildcard instances of Java generics

This article mainly introduces the analysis of common wildcard examples of Java generics. The example code is introduced in great detail, which has a certain reference value for everyone's study or work. Friends in need can refer to it

Today, I was looking at the original code of ArrayList. I was curious to see such a symbol.

? Indicates a wildcard, which means that it matches e or a subclass of e. the specific type is unknown.

1. Qualified wildcards

Write a dynamic data similar to 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 void main(String[] args) {
    Gys<Number> gys=new Gys<>();
    gys.add(25);
    Gys<Integer> gys2=new Gys<>();
    gys2.add(2);
    gys.addAll(gys2);
  }
}

Modify the above code and change the addall parameter to the following

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

At this time, the code has been compiled. And can normally access the elements.

2. Infinite wildcard.

Rewrite the addall method code above.

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

The above code failed to compile.? The representation type is uncertain. Considering the indefinite generic type from the perspective of security, it is impossible to write. But it can be used like this.

/**
   *判断元素是否存在
   */
  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;
  }

Except usage; And indicates that the type is e or the parent class of E. However, the introduction is too much and the use is too little.

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>