tags:

views:

58

answers:

2

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;
}
+3  A: 

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.

Andrei Fierbinteanu
A: 

Editted to answer your question better, and removed c# version :)

By returning a ReturnContainer, you are giving information about the returned type of the inner objects.

By only passing in information about the Class incoming, you are not giving information about the ReturnContainer as such, or the elements within it - just that the parameter is of type T.

tim
Yes they will compile, you can declare a method with a generic type parameter. Your version does not compile: `Syntax error on token "<"`. I'm not sure what you where trying to do, but you can't declare a method like `methodName<type>` in Java.
Andrei Fierbinteanu
LOL. Read it as a C# question. My bad :)
tim
i've removed my little moment of madness - basic explanation stands, but it seems you have covered that now anyway.
tim