Using a parameterized (generic) Java class compared to a regular class

if I need to write a class that works with data like "Comparable", I can do this in two ways:

1)

public class MyClass<T extends Comparable>
{

    private T value;

    MyClass(T value)
    {
        this.value = value;    
    }

    other code...
}

2)

public class MyClass
{

    private Comparable value;

    MyClass(Comparable value)
    {
        this.value = value;    
    }

    other code...
}

which of these two approaches is better, and why? In general, if and why is it better to use Generics when the same thing can be achieved without using them?

+3
source share
6 answers

It depends on the rest of your class. If, for example, you have a method getValue, then a general approach is preferable, since you can do this:

public class MyClass<T extends Comparable>
{

    private T value;

    MyClass(T value)
    {
        this.value = value;    
    }

    T getValue() {
        return this.value;
    }

    other code...
}

Without generics, some type information will be lost, since you can only return Comparable.

+6
source

, . Generics , , . , ; Comparable, , , Comparable<T> T; , , , .

+4

. - erasure () .

, , , . , . :

public class MyClass<T extends Comparable<? extends SomeBaseClass>>
{

    private T value;

    MyClass(T value)
    {
        this.value = value;    
    }

    // other code...
}

, , .

+2

, . , . .

//Generic class 
class CGeneric<T extends Comparable>
{
    private T obj;
    public T getObj() { return obj; }
    public void setObj(T value) { obj = value;: }
}

//Non-generic class
class CNormal
{
  private Comparable obj;
  public Comparable getObj() { return obj; }
  public void setObj(Comparable value) {obj = value;}
}

getObj CGeneric MyComparable ( , ). getObj CNormal, Comparable ( ), MyComparable, , .

, typechecks , CastException.

+1

, ( ). , . 1.

0

, : , . T ? , . , , , : T Comparable <T> , , , , , :

Foo Comparable < >

So the actual implementation should be T extends Comparable <? super T>. Nice and not so difficult. But then we get things like Enum <E extends Enum <E โ†’ and really, explain it to someone without confusing it - good luck with that.

So, Generics are useful and easy to use, but extremely difficult for WRITE to do correctly (and don't make me start writing the right binary backward compatible versions of the existing library - see the lib compilation in the JDK). Fortunately, only a small portion of library writers need this right for everyone else to benefit from it.

0
source

All Articles