Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java infinitely recursive self referential types

I'm trying to create an implementation of Map that takes collections as keys.

What do you even call this conundrum?

What is the right way to do the class signature?

class SubClass <K extends Collection<E>, V> implements Map<K, V>

^^ Is improper syntax, but indicates what I want to do.

class SubClass <K extends Collection<K>, V> implements Map<Collection<K>, V>

^^ Results in a SubClass for which you can never declare the generic type. K is infinitely recursive. It also doesn't describe the type of behavior I'm looking for.

class SubClass <K , V> implements Map<K, V>

^^ Doesn't enforce the constraint that K needs to be a Collection

class SubClass <K extends Collection, V> implements Map<K, V>

^^ Doesn't allow us to know the generic types of the Collection

class SubClass <E, K extends Collection<E>, V> implements Map<K, V>

^^ Works, but is rather unwieldy

like image 227
kag0 Avatar asked Mar 16 '23 17:03

kag0


1 Answers

You'll need a type parameter for the Collection element type, potentially a type parameter for the actual Collection type if you need it, and a type parameter for the values.

class SubClass<E, K extends Collection<E>, V> implements Map<K, V> { ... }

If you don't need the specific Collection type, you can use

class SubClass<E, V> implements Map<Collection<E>, V> { ... }

Concerning the various comments on your question

public class Example {
    public static void main(String[] args) throws Exception {
        Whatever<Self> s = new Whatever<>();
    }
}

class Self extends ArrayList<Self> {
}

class Whatever<E extends Collection<E>> {
}
like image 172
Sotirios Delimanolis Avatar answered Mar 22 '23 23:03

Sotirios Delimanolis