简体   繁体   中英

How to define a concrete type constructor inside a generic class

Trying to define a concrete type constructor inside a generic class, but got the following errors. Anyone knows how to fix this? Thanks.

public class GenericStack<E>{
    private java.util.ArrayList<E> list=new java.util.ArrayList<>();

    public GenericStack(String a){
            this.push(a);
    }
    public int getSize(){
            return list.size();
    }

    public E peek(){
            return list.get(getSize()-1);
    }

    public void push(E o){
            list.add(o);
    }

    public E pop(){
            E o=list.get(getSize()-1);
            list.remove(getSize()-1);
            return o;
    }

    boolean isEmpety(){
            return list.isEmpty();
    }

    @Override
    public String toString(){
            return "Stack"+list.toString();
    }

    public static void main(String[] args){
            GenericStack<String> stack1=new GenericStack<>("testmessage");

            System.out.println(stack1);
    }

}

Get the following error:

GenericStack.java:6: error: incompatible types: String cannot be   converted to E
    this.push(a);
              ^
where E is a type-variable:
E extends Object declared in class GenericStack

Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output 1 error

If you're trying to define a constructor for a stack containing strings, you can't. Constructors and other instance methods have to work for all types within the type variable's bounds.

But you can define a static factory method which only creates instances of GenericStack<String> :

static GenericStack<String> create(String e) {
  GenericStack<String> s = new GenericStack<>();
  s.push(e);
  return s;
}

定义构造函数参数以匹配为类定义的类型

public GenericStack(E a) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM