-2

I am trying to make my own type of list class using generics. This list can be a list of double or string. So I can call on it:

myList<Double> l1=new myList<Double>();

I am new to using generics so I am not quite sure how to achieve this. What I have so far is:

class myList<T> {
   List<T>list=new List<T>();
     myList(T list){
        this.list=list;
    }
    public void add(T o){
        list.add(o);
    }
}

Right now it gives me the error: "cannot find symbol

List<T>list=new List<T>();
mijmajmoj
  • 71
  • 5
  • 1
    `List` is an interface. You need to construct a concrete implementation, like `ArrayList`. – shmosel May 16 '22 at 00:18
  • 1
    Try `java.util.List list = new java.util.ArrayList<>();` -- also, you won't get a default constructor. So you should add an empty constructor (or you can't do `new myList();`) And class names should start with a capital letter. – Elliott Frisch May 16 '22 at 00:21
  • You also need to import `java.util.List` if you are going to use it without qualifying it. It seems to me that you should be learning *basic* Java before you leap into writing generic classes. Understanding interfaces vs classes and the need for `import` statements are both "basic Java" things ... – Stephen C May 16 '22 at 00:26
  • Also, the constructor doesn't make sense. You can't assign a `T` to a `List` field (unless `T extends List`). – shmosel May 16 '22 at 00:34
  • Also for completeness the Java collections have abstract classes like `AbstractList` and `AbstracSet` that are designed to make it easy to create your own collections classes (like `MyList`). https://docs.oracle.com/javase/7/docs/api/java/util/AbstractCollection.html – markspace May 16 '22 at 00:35
  • Have you imported `List`? As in, does your code have `import java.util.List;` near the top, above the class definition? – davidalayachew May 16 '22 at 04:31

0 Answers0