Search code examples
javaoopgenericsmethodsgeneric-collections

How to make this Java method generic


I have a java method that i'm trying to make generic so that it can take a list of 2 different types of object as a parameter. (Trivial example shown below). These 2 different objects will both always have the methods getDate() and getHour(). The code looks like this:

public <T> List<T> getListOfStuff(List<T> statistics) {

    List<T> resultList = new ArrayList<T>(statistics.size());

    if(statistics.size() > 0){
        resultList.add(statistics.get(0));

        int date = Integer.parseInt(resultList.get(0).getDate());
        int hour = Integer.parseInt(resultList.get(0).getHour());
    }
    return resultList;
}

However this doesn't work. These two lines don't work:

int date = Integer.parseInt(resultList.get(0).getDate());
int hour = Integer.parseInt(resultList.get(0).getHour());

The errors say: "The method getDate() is undefined for the type T" and "The method getHour() is undefined for the type T"

It offers me a suggestion to add a cast to the method receiver but it won't let me use T and instead forces the object name upon me like this which won't work for me:

int date = Integer.parseInt((ObjectName1)resultList.get(0).getDate());
int hour = Integer.parseInt((ObjectName1)resultList.get(0).getHour());

Is there any way to do what I want here?


Solution

  • You'll want to use the following:

    public <T extends ObjectName1> List<T> getListOfStuff(List<T> statistics) {
        List<T> resultList = new ArrayList<>(statistics.size());
    
        if (!statistics.isEmpty()) {
            resultList.add(statistics.get(0));
    
            int date = Integer.parseInt(resultList.get(0).getDate());
            int hour = Integer.parseInt(resultList.get(0).getHour());
        }
    
        return resultList;
    }
    

    The only Lists that can be passed to this method now must either hold ObjectName1 or an object that extends it.