Naor
Naor

Reputation: 24083

convert Collection<MyType> to Collection<Object>

I have a class with the following constructor:

public UniqueField(Collection<Object> items) {
      this.items=items;
}

The idea behind the Collection<Object> is that I would be able to use Collection<OtherType>.

When doing:

Collection<OtherType> collection=... 
new UniqueField(collection);

I getting a compile error of invalid argument. How can I fix this?

Upvotes: 0

Views: 164

Answers (2)

Simon LG
Simon LG

Reputation: 2997

You have to use this instead

public UniqueField(Collection<? extends Object> items) {
      this.items=items;
}

or ? because it is equal to "? extends Object"

public UniqueField(Collection<?> items) {
      this.items=items;
}

You can see here for the reason

Upvotes: 4

you can use either:

public UniqueField(Collection<?> items) {
      this.items=items;
}

or:

public UniqueField(Collection<? super OtherType> items) {
      this.items=items;
}

or simply:

public UniqueField(Collection<OtherType> items) {
  this.items=items;
}

Upvotes: 0

Related Questions