2

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 ?

1
  • If you write the two methods, compile them, and then view the bytecote with javap, you can see for yourself. Commented Feb 13, 2016 at 0:43

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.