- Only instances of that type can be inserted
List<T> list = new ArrayList<T>();
- list − object of List interface.
- T − The generic type parameter passed during list declaration.
Example:
import java.util.ArrayList;
import java.util.List;
public class GenericList <T>{
List<T> wrappedList;
public GenericList() {
this.wrappedList = new ArrayList<>();
}
public GenericList(List<T> wrappedList) {
this.wrappedList = wrappedList;
}
//get method with custom one
public T myGet(int index){
return wrappedList.get(index);
}
//add method with custom one
public void myAdd(T o){
wrappedList.add(o);
}
//remove method with custom one
public T myRemove(int index){
return wrappedList.remove(index);
}
@Override
public String toString() {
return wrappedList.toString();
}
public static void main(String[] args) {
GenericList<CharSequence> g = new GenericList<>();
g.myAdd("hi");
g.myAdd("hello");
var o = g.myGet(0);
System.out.println("Element 0 = "+o);
System.out.println("Wrapped List "+g.myRemove(0));
}
}
No comments:
Post a Comment