简体   繁体   中英

How to create a method that retrieves a sublist containing elements of a specific class T?

I have the following function

public <T> T getItemsByType(){
    T[] retarr = null;
    for(int i = 0; i<items.size(); i++){
        if(items.get(i).get instanceof T){

        }
    }
    return null;
}

I need my function to search in a list of items for instances of type T and then return an array of T.

Of course, this would've been great if worked but the problem is that:

Cannot perform instanceof check against type parameter T. Use its erasure Object instead since further generic type information will be erased at runtime

What should I do to obtain the same effect?

You need to pass Class<T> clazz as argument to your method, then use it to check if the element can be assignable to that class by using Class#isInstance .

public <T> T getItemsByType(Class<T> clazz) {
    T[] retarr = null;
    for(int i = 0; i<items.size(); i++){
        if(clazz.isInstance(items.get(i))){
            //do your logic here...
        }
    }
    return null;
}

Some recomendations:

  • It would be better returning a List<T> or Collection<T> instead of returning a single T element.
  • Avoid returning null , so you don't have to do null -defensive programming.
  • Use an iterator or an enhanced for loop to traverse through all the elements in your list.

So, a better implementation would be:

public <T> List<T> getItemsByType(Class<T> clazz) {
    List<T> theList = new ArrayList<T>();
    //using Object since you never specified which type of elements holds this list
    for (Object o : items) {
        if(clazz.isInstance(o)) {
            //do your logic here...
            theList.add(clazz.cast(o));
        }
    }
    return theList;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM