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.
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.
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.
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.
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.
public class Foo<T extends A & B> {
private List<T> list;
//getters, setters, etc.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With