Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return object typed with generic class type

Tags:

java

generics

The code below contains a getter to a Set of objects with class T:

public class Cube <T extends State> {

   private Set<T> states = new HashSet<>();

   public Set<T> getStates() {
      return states;
   }

} 

Which seemed to me the valid way to return a the Set of states. However, it returns a set of Objects instead. Trying to use:

Cube<DestinationState> cube = new Cube<>();
Set<DestinationState> set = cube.getStates();

Yields a compile error on the second line:

Error:(187, 61) java: incompatible types: java.lang.Object cannot be converted to nl.gijspeters.pubint.graph.state.DestinationState

State is a generic interface with multiple implementation classes (among which DestinationState) and subinterfaces.

This may very well be a duplicate question (as it seems quite basic), however, I was not able to find the answer.

like image 946
Gijs Peters Avatar asked Jan 18 '26 04:01

Gijs Peters


1 Answers

by default T is replaced with Object so this is type inference based on the target so try this

Set<DestinationState> set = cube<DestinationState>.getStates();
like image 191
Pavneet_Singh Avatar answered Jan 19 '26 19:01

Pavneet_Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!