简体   繁体   中英

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?

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 List s that can be passed to this method now must either hold ObjectName1 or an object that extends it.

Your method specifies to use a type T about which all the compiler knows is that it extends Object . Object does not have the methods you invoked. You have to assert that the type has the methods you use. For that you need <T extends Foo> , where Foo is a type with those methods.

ObjectName1 is one of the worst names for a type possible.

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