Generics mismatch type

Here's the interface:

public interface Foo<T> extends Comparable<Foo<T>>  {
   ...
}

And there are some classes that implement this interface:

public class Bar extends Something implements Foo<Something> {
    public Vector<Foo<Bar>> giveBar() {
        ...
    }
}

public class Boo extends SomethingElse implements Foo<SomethingElse> {
    public Vector<Foo<Boo>> giveBoo() {
        ...
    }
}

Now I want to save a bunch of Foos (it could be Foos or Boos) inside the vector.

Bar bar = new Bar();
Boo boo = new Boo();
Vector<Foo<?>> vector;
if (...) 
   vector = bar.giveBar();
else
   vector = boo.giveBoo();

I get:

Type mismatch: cannot convert from Vector<Foo<SomethingElse>> to Vector<Foo<?>>

The same goes for:

Vector<Foo> vector;
if (...) 
   vector = giveBar();
else
   vector = giveBoo();

Is it a superclass that both Bar and Boo extend the only solution to this problem?

+3
source share
2 answers

That all this code comes down to the following:

Vector<A> vector = new Vector<B>();

In this case, B extends A, but this is not allowed because the types do not match. To understand why this does not work, imagine the following code:

Vector<Vector<?>> vector = new Vector<Vector<String>>();
vector.add(new Vector<Integer>());

; , , . . Vector<?>, Vector<Integer>; Vector<String>, . , , .

# , , # , Java .

ps - Vector LinkedList ArrayList? , ?

+6

Vector<? extends Foo<?>> vector;
+2
source

Source: https://habr.com/ru/post/1699046/


All Articles