Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to make type safe Java Collections whose members merely implement several interfaces?

Tags:

java

generics

If I have:

interface A{  void a();  }
interface B{  void b();  }

I can hava a generic method like this:

class C {
    <T extends A & B> void c(T t) {
        t.a();
        t.b();
    }
}

But i can't hava a generic collection like this:

class D{
    List<? extends A & B> l;
}

I know that I could make an empty interface E that extends both A and B, and have a List that contains E's... but I'd rather leave my classes marked with just A and B, and not have to have an E. This is even more problematic when there are many more A's and B's that can be combined in 2^n ways.

I would rather be able to define a type on the fly, as a union of interfaces, and have the collections recognize objects that implement all of the interfaces as instances of that type.

Is there a way to do this in Java? I'm open to any kind of work around or hack at this point in order to avoid making a new interface, and tagging my classes with it, just so that they can live together in a collection. Or, if someone could clarify for me why this is impossible, that would be equally appreciated.

like image 769
Ben Horner Avatar asked Apr 02 '12 00:04

Ben Horner


People also ask

Can you implement multiple interfaces in Java?

Your class can implement more than one interface, so the implements keyword is followed by a comma-separated list of the interfaces implemented by the class. By convention, the implements clause follows the extends clause, if there is one.

Which Collection is type safe?

Type safe means passing the data, according to the datatype or an object, we used at the time of initialization. You can use Int, String, Float or any Class you defined, while using list. Another collection that comes under Generic is Dictionary.

What are the types of collections allowed by the Java Collections Framework?

Three Types of Collection There are three generic types of collection: ordered lists, dictionaries/maps, and sets. Ordered lists allows the programmer to insert items in a certain order and retrieve those items in the same order.

Can many classes implement the same interface?

A class can implement many interfaces but can have only one superclass. An interface is not part of the class hierarchy. Unrelated classes can implement the same interface.


1 Answers

public class Foo<T extends A & B> {
    private List<T> list;
    //getters, setters, etc.
}
like image 55
Jeffrey Avatar answered Sep 25 '22 20:09

Jeffrey