M. os.i M. os.i - 7 months ago 12
Java Question

How to override java list methods?

I'm working on a java project where i need to use lists of different types that I create (Student ,school ... for example).

The problem is that I need to use some list methods with this types(or classes) like "containe" for Ex ...

I try to override this methods by creating my own list(arraylist or vector) which is Extended from java list ... but I have many problems because I want to use this new list(my list) with different types .

This how I extends myList from java list:

public class myList extends ArrayList<Object>{

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


and this how I use it :

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


But it does not work. So what is the right way to do this.

and thanks.

Answer

What you are looking for are Generics:

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

This way you can create your own list of whatever you want like this:

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

Response Update:

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);