gpt4 book ai didi

java - 如何重写java列表方法?

转载 作者:行者123 更新时间:2023-11-30 07:25:40 24 4
gpt4 key购买 nike

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

问题是我需要使用一些具有这种类型(或类)的列表方法,例如“containe”对于 Ex ...

我尝试通过创建自己的列表(数组列表或 vector )来覆盖此方法,该列表是从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);

关于java - 如何重写java列表方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36840759/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com