0
votes

i have multiple classes that are very different between them , so i CAN'T extends all from one generic parent, beside Object

some of this classes implements an interface, called "Searchable" , others no

i have a class that extends ArrayList

public class ItemList<Object> extends ArrayList<Object>

and the generic Object for this list allow me to use this list for ALL my classes

now, for the only classes that implements that interface, i want to have an extension of ItemList , calling it "SearchList", that allow me to do some operations with method of the the interface if one method of Searchable is "search(int x)" i want a method in "SearchList" like this

public int count(int x){
int ret=0;
       for(int i=0;i<this.size();i++{
            ret=ret+this.get(i).search(x);
        }
return ret;
}

how can i do something like this? becouse i know that i can't use generics

thanks for the help :)

3
SomeClass<Object> extends ArrayList<Object> is redundant imo - Rogue
Please do not name your type parameter "Object" - newacct

3 Answers

0
votes

If some of your elements implement the Searchable interface, then you can test them using the instanceof operator.

for(Object o : this) {
    if(o instanceof Searchable) {
        Searchable s = (Searchable)o;

        // Do what you need to with it.
    }
}

NOTE: I wouldn't recommend extending ArrayList for this type of usage. Composition fits this a lot nicer.

0
votes

If you want a list containing only Searchable object, you can do :

public class SearchList<Searchable> extends ItemList<Object>
0
votes

So you want SearchList to extend ItemList, but take only type arguments that extend Searchable?

public class SearchList<T extends Searchable> extends ItemList<T>