-1

Is there any differences between those two class declarations

1:

class MyClass <T extends Number & Comparable>

2:

class MyClass <T extends Number & Comparable<T>>

I think that there are differences. But I cannot find an example which would show differences because I don't understand it exact.

Can you show me this example?

arshajii
  • 127,459
  • 24
  • 238
  • 287
gstackoverflow
  • 36,709
  • 117
  • 359
  • 710

1 Answers1

5

There is a difference. The first one is using raw types, and thus, is less type-safe. For example:

This works, but should not work

class MyClass<T extends Number & Comparable>
{
    void use(T t)
    {
        String s = null;
        t.compareTo(s); // Works, but will cause a runtime error
    }
}

Whereas this does not work (because it should not work)

class MyClass<T extends Number & Comparable<T>>
{
    void use(T t)
    {
        String s = null;
        t.compareTo(s); // Compile-time error
    }
}

EDIT: Full code, as requested:

class MyClass<T extends Number & Comparable>
{
    void use(T t)
    {
        String s = "Laziness";
        t.compareTo(s); // Works, but will cause a runtime error
    }
}


public class MyClassTest
{
    public static void main(String[] args)
    {
        MyClass<Integer> m = new MyClass<Integer>();
        Integer integer = new Integer(42);
        m.use(integer);
    }
}
Marco13
  • 53,703
  • 9
  • 80
  • 159