Type mismatch with generics

Here's an interface:

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

And there are some classes implementing 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 keep a bunch of Foos (that may really be Foos or Boos) inside a vector.

Bar bar = new Bar();
Boo boo = new Boo();
Vector<Foo<?>> vector;
if (...) 
   vector = bar.giveBar();
   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();
   vector = giveBoo();

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

Asked by: Grace777 | Posted: 21-01-2022

Answer 1

What all that code boils down to is:

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

In this case B extends A, but that's not allowed because the types don't match. To make clear why this doesn't work, imagine the following code:

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

The variable's type is of a vector of vectors of unknown type; and what's being assigned to it is a vector of vectors of strings. The second line adds a vector of integers to that. The component type of the variable Vector<?>, which accepts Vector<Integer>; but the actual vector's component type is Vector<String>, which doesn't. If the compiler didn't object to the assignment on the first line, it would allow you to write the incorrect second line without being spotted.

C#'s generics have a similar restriction, but the difference is that a generic class in C# stores it component type, while Java forgets component types when the code is compiled.

ps - Why on earth are you using Vector rather than LinkedList or ArrayList? Is it because there are threading issues involved?

Answered by: Wilson932 | Posted: 22-02-2022

Answer 2

You can use

Vector<? extends Foo<?>> vector;

Answered by: Grace678 | Posted: 22-02-2022

Similar questions

java - Bound Mismatch Generics

I have below class hierarchy. First class class First&lt;T&gt; { } Second class class Second&lt;T&gt; extends First&lt;T&gt; { } Third Class class Third&lt;T extends First&lt;T&gt;&gt; { } Error line: Third&lt;Second&lt;String&gt;&...

Bound mismatch for java generics for a spring app

I am trying to create a REST api using Spring MVC. Instead of writing CRUD methods for each of the controller, I created an abstract class that would take care of the typical REST CRUD scenarios. So I created these following classes public interface DomainObject&lt;ID extends Serializable&gt; {} public class Apps implements DomainObject&lt;String&gt;{} public interface AppsRepository extends PagingAndSort...

Bound mismatch with Java Generics "nesting"

I'm having difficulty using generics for a redesign/refactoring I'm doing on an existing design. public interface DataDto { // some data here } public interface SetDto&lt;MyDataDto extends DataDto&gt; { List&lt;MyDataDto&gt; getData(); } public interface Results&lt;MySetDto extends SetDto&lt;DataDto&gt;&gt; { MySetDto getResults(); } public interface MyProblemInterface&lt;MyDataDto extends Da...

Bound mismatch warning in java generics

Please have a look at below code listing :- package com.test; class XParam implements Comparable&lt;XParam&gt;{ @Override public int compareTo(XParam o) { // TODO Auto-generated method stub return 0; } } public class Main { public static void main(String[] args) { Comparable&lt;XParam&gt; param = new XParam() ; SomeClass object = new SomeClass() ; ...

Bound Mismatch error java generics

Getting the error Bound mismatch: The generic method insertData(TreeNode, E) of type BinarySearchTree is not applicable for the arguments (TreeNode, T). The inferred type T is not a valid substitute for the bounded parameter > What is wrong with the below code? public class BinarySearchTree&lt;T extends Comparable&lt;? extends T&gt;&gt; ...

Type Mismatch error in Java generics

This question already has answers here:

java: bound mismatch when using generics

I am trying to implement a generic binary tree. Here's the declaration of the node class public abstract class Node&lt;E extends Comparable&lt;E&gt;&gt; { } A concrete Node: public class BinaryTreeNode extends Node&lt;BinaryTreeNode&gt; implements Comparable&lt;BinaryTreeNode&gt; { @Override public int compareTo(final BinaryTreeNode node) { if (this...

java - How to safely fix this type mismatch on abstract method with generics and Supplier lambda

We have a cache framework which we use to wire application-specific cache types (such as this authentication cache shown below) to various implementations (e.g. ehcache, redis, memcached etc). The framework is just an abstraction layer to allow the application to define and manipulate its cache similar to a map of key-value pairs, while specifying its app-specific key class and value class. So for example we have:

java - Bound mismatch error using Generics for an object array

I have used the comparable interface before but using it with generic objects and a second object has been causing me some difficulties Here is my driver program import java.io.*; import java.util.*; public class Prog2 { public static void main (String[]args){ //Declare Variables Scanner inFile = null; ListArray&lt;Part&gt; partArray = new ListArray&lt;Part&gt;(13); //Op...

Java Generic Casting Type Mismatch

public class MaxHeap&lt;T extends Comparable&lt;T&gt;&gt; implements Heap&lt;T&gt;{ private T[] heap; private int lastIndex; public void main(String[] args){ int i; T[] arr = {1,3,4,5,2}; //ERROR HERE ******* foo } public T[] Heapsort(T[]anArray, int n){ // build initial heap T[]sortedArray = anArray; for (int i = n-1; i&lt; 0; i--){ //assert: the tree rooted at index is a semiheap...

java - Type mismatch error

I am trying to create a list of list of strings, List&lt;List&lt;String&gt;&gt; string= new ArrayList&lt;ArrayList&lt;String&gt;&gt;(); and getting Type Mismatch error:cannot convert from ArrayList&lt;ArrayList&lt;String&gt;&gt; to List&lt;List&lt;String&gt;&gt;. I know I can change List&lt;List&lt;String&gt;&gt; to ArrayList&lt;ArrayList&...

iphone - Tag mismatch error when using java web service WSDL with gsoap C client

I have created C client for the java Axis 1.4 Web service WSDL, using wsdl2h and soapcpp2 tool of gsoap 2.7.17. I'm using these soap client in my iphone application. I'm able to compile the application successfully. But, when I try to call a function of from the client file, it returns nil value in the response structure, but return code of the function call is SOAP_OK. I tried debugging the soap fi...

java - Android test class fails to compile in eclipse with "bound mismatch" error

I'm writing testcases for an android app extending ActivityInstrumentationTestCase2. The test class looks like this: public class SolutionEntryActivityTest extends ActivityInstrumentationTestCase2&lt;SolutionEntryActivity&gt; { public SolutionEntryActivityTest() { super(SolutionEntryActivity.class); } } In eclipse, this code fails to compile with the error:

java - Shared PK in entity mismatch

I'm developing an example web-application, using JPA 2.0 entities, Hibernate 3.6.2 and Spring 3. The example contains two tables in a one-to-one relationship, the parent entity is Client and the child is Address, the PK in Address references the Client table (identifying relationship). Running the JUnit tests, I've noted a peculiar problem with these two entities, the problem it's that the child entity persists wit...

java - How to avoid "Type mismatch" in static generic factory method?

Either I'm too stupid to use google, or nobody else encountered this problem so far. I'm trying to compile the following code: public interface MyClass { public class Util { private static MyClass _this; public static &lt;T extends MyClass&gt; T getInstance(Class&lt;T&gt; clazz) { if(_this == null) { try { _this = clazz.newInstance(); } catch(Exception e) { ...

Java: Generic Type type mismatch syntax error

I have this declaration/initiation written for Java JDK 1.6 Map&lt;String, &lt;? extends List&lt;?&gt;&gt;&gt; groupThemTogether = new HashMap&lt;String, ArrayList&lt;String[]&gt;&gt;(); The error happens at the first comma. The error message is Type mismatch: cannot convert from HashMap&lt;String,ArrayList&lt;String[]&gt;&gt; to Map&lt;String,List&gt;

arrays - Why do I get a type mismatch when trying to reverse a string in Java?

So, I was always a novice programmer but recently decided to learn Java. I was just messing around with a small constructor that was to take in a string and then write it backwards (my method of doing this was in no way supposed to be efficient, I was simply using different tools available to me in order to become accustomed.) My error came when I was trying to add a char in an array to a string. This is the code: ...

java - Type mismatch in object factory

I'm using a very simple factory class to create an initialize some of my objects: public class MyFactory { public static Superclass createObject(String type) { Superclass myObject = null; if (type.equals("type1")) { myObject = new Subclass(); myObject.setParam("val1"); } return myObject; } } Not that complex :-) ...

java - How to return an object of type "Object" without causing a type mismatch

How can I return type Object from a method to an unknown type without causing a type mismatch?

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)