Difference between: ReturnContainer test() and: ReturnContainer test()?

What is the difference between the signatures of the two methods below?

public static <T> ReturnContainer test(Class<T> incomingClass)
{
    List<TestTuple<T>> tupelo = new ArrayList<TestTuple<T>>();
    ReturnContainer rc = new ReturnContainer(tupelo, incomingClass);
    return rc;
}

What’s the difference between requiring a return type of <T> ReturnContainer above versus <T> ReturnContainer<T> below?

public static <T> ReturnContainer<T> test(Class<T> incomingClass)
{
    List<TestTuple<T>> tupelo = new ArrayList<TestTuple<T>>();
    ReturnContainer rc = new ReturnContainer<T>(tupelo, incomingClass);
    return rc;
}

Answer

Well, if ReturnContainer is a generic class, which I’m assuming it is from your examples, it’s not recommended to use raw types like in the first example, since it’s not type safe.

For example you might have something like:

ReturnContainer<String> container = test(Integer.class);

This would work (but would produce a warning) since the return type is a raw type. Then when you would try to get something from the container, the compiler would believe it’s a String, but it’s actually an Integer and you would get a ClassCastException.

Edit: after looking at your previous question

You need to tell us if ReturnContainer has a type parameter in the first place, or what the point of the class is. A <T> parameter is useful on container classes like Lists or Maps, since it tells you directly what type of objects it contains, as opposed to carrying Objects and letting you cast them to anything when you retrieve them from the container. They offer extra type safety. You know for sure that a List<String> is guaranteed to only contain Strings, and it’s get and add methods only return/accept Strings. If your container has similar behavior, than it should have a type parameter, and you should use the second method.

Leave a Reply

Your email address will not be published. Required fields are marked *