如何覆盖 java 列表方法?

How to override java list methods?

我正在做一个 java 项目,我需要使用我创建的不同类型的列表(例如学生、学校...)。

问题是我需要对这种类型(或 类)使用一些列表方法,例如 "containe" for Ex ...

我尝试通过创建我自己的列表(数组列表或向量)来覆盖此方法,该列表是从 java 列表扩展的...但是我有很多问题,因为我想使用这个新列表(我的列表) 具有不同的类型。

这是我从 java 列表扩展 myList 的方式:

public class myList extends ArrayList<Object>{

public myList() {
}
    /***methods***/
}

这就是我的使用方式:

public class newclass(){
       .
       .
       .
    myList<student> sl=new myList<student>();
       .
       .

但是不行。那么正确的做法是什么。

谢谢。

您要找的是Generics:

public class myList<T> extends ArrayList<T> {
...
}

这样您就可以像这样创建自己的列表:

myList<student> sl = new myList<>();

响应更新:

how to make get -for example- return the same type in declaration -which is instead of the type Object

回复您的列表

myList<student> sl = new myList<>();
sl.add(new student());
student s = sl.get(0);

响应 ArrayList:

// But it works also with an ArrayList which implicitly mean that you have no need 
// to create your own implementation of an ArrayList
List<student> sl = new ArrayList<>();
sl.add(new student());
student s = sl.get(0);