I read much about Generics recently.
public static <T extends CharSequence> void prnt(T obj);
public static void prnt(CharSequence obj);
Is there any difference between both ?
I read much about Generics recently.
public static <T extends CharSequence> void prnt(T obj);
public static void prnt(CharSequence obj);
Is there any difference between both ?
For your example it does not really make a difference.
Where it makes a difference is the following example:
public static CharSequence foo1(CharSequence c) {...}
public static <T extends CharSequence> T foo2(T t) {...}
Both will return an object that is a subtype of CharSequence but the second one allows more flexibility. Imagine the following code:
String s = "test";
CharSequence c = s;
CharSequence c1 = foo1(c);
CharSequence c2 = foo2(c);
This works fine just as you expect.
CharSequence c1 = foo1(s);
String s2 = foo2(s);
Here we see why it might make sense to declare the function using generics. With <T extends CharSequence> we can enforce that the function only works with subclasses of CharSequence without losing the information about the actual type. The first method on the other hand will lose this information and maybe even force you to have a cast which is really ugly.
IN your case they're equal, They both work on something that implements CharSequence.
In the general case they're not equal at all!
For instance imagine to return T in the first case and CharSequence in the second as follows:
public static <T extends CharSequence> T prnt(T obj);
public static CharSequence prnt(CharSequence obj);
Let's use both with CharBuffer (that implements CharSequence)
public static CharBuffer prnt(CharBuffer obj);
public static CharSequence prnt(CharSequence obj);
As you see they're not equal at all.