javagenerics

Is there a Union in Java Generics?


Can I contain two different types in a collection? For example, can I have List< String U Integer > ?


Solution

  • Short answer? No. You can (of course) have a List of Objects, but then you can put anything in it, not just String or Integer objects.

    You could create a list of container objects, and that container object would contain either an Integer or String (perhaps via generics). A little more hassle.

    public class Contained<T> {
       T getContained();
    }
    

    and implement Contained<Integer> and Contained<String>.

    Of course, the real question is why you want to do this? I would expect a collection to contain objects of the same type, and then I can iterate through and perform actions on these objects without worrying what they are. Perhaps your object hierarchy needs further thought?