Strongly Typing List and ArrayList - Generics?
I'm trying to solve a classic case. I want to create a custom List and ArrayList that work with only one type of object and provide some additional functionality related to that object.
Traditionally one would just extend List/ArrayList, create type-specific methods to work with the list and check for casting errors. I was wondering with the introduction of Generics if there was a simpler way of doing this WITHOUT having to recreate all of those add, indexOf, etc methods?
For example, assume I have a class:
publicclass Thingie{
protected String name;
public Thingie(String name){
super();
this.name = name;
}
public String getName(){
return name;
}
publicvoid setName(String name){
this.name = name;
}
}
And I have a List:
publicinterface ThingieListextends List{
publicvoid printAll();
}
And I have an ArrayList:
publicclass ThingieArrayListextends ArrayListimplements ThingieList{
publicvoid printAll(){
ListIterator iter = this.listIterator();
while (iter.hasNext()){
Thingie thingie = (Thingie) iter.next();
System.out.println(thingie.name);
}
}
}
And a simple class to use these objects:
publicclass ListTester{
publicstaticvoid main(String[] args){
ThingieList list =new ThingieArrayList();
list.add(new Thingie("One"));
list.add(new Thingie("Two"));
list.add(new Thingie("Three"));
list.add(new String(""));// Will cause an error, but is not detected
// by compiler
list.printAll();
}
}
Is there a way, using Generics or some other method to Make ThingieList and ThingieArrayList ONLY accept Thingies? Right now I can add any time of object to my ThingieList and won't get an error until runtime.
Thanks,
Leo

