Using parameterized (generic) Java classes and normal classes

If I need to write a class that handles' comparable 'data, I can do it 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 the two methods is better and why? In general, is it better to use generics if you do the same thing without using them?

Solution

It depends on the rest of your class For example, if you have a method getValue, the generic method is better because 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 because you can only return a comparable

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>