aszex
aszex

Reputation: 43

Collection of abstract generic class, raw type warning

I have following class hierarchy:

public abstract class Property<T>
{
    private long id;
    private String name;
    private T value;

    /*setters and getters*/
}

public class NumberProperty extends Property<Integer>

public class TextProperty extends Property<String>

...and a class containing List<Property> properties. I get "Property is raw type. References to generic type Property<T> should be parametrized". I know why, but I want to have one list of properties of few, known types (Property cannot be instatiated as it is abstract class).

My question is: can I ignore the warning or should I change my code (how?) ?

Upvotes: 2

Views: 1200

Answers (3)

mthmulders
mthmulders

Reputation: 9705

Since it's a warning, you can always choose to ignore it ;).

The warning informs you that when you have a List<Property>, you don't know what comes for the <T> in the Property class. If you're not sure, you can use List<Property<?>> to indicate that anything will do.

Refer to Oracles generics tutorial to learn more on this topic.

Upvotes: 1

Marko Topolnik
Marko Topolnik

Reputation: 200168

Collections in Java are homogeneous, so it is an error to put values of varying types into them. Note that Property<Integer> is not hierarchically related to Property<String>—these are two disparate types and the Java type system will not be able to represent your list where some properties are strings and some integers. Your only option is to lose type safety.

Upvotes: 1

dacwe
dacwe

Reputation: 43504

Use Property<?> if you don't care about which type of object it is this will instruct the compiler that you know what you are doing.

List<Property<?>> list;

Upvotes: 6

Related Questions