Java wildcarding with multiple types in variable

I know it is possible to wildcard with multiple types in case of methods and classes but what about variables? E.g. can I require an ArrayList to only take elements that implement both of two different interfaces that are not in the same type hierarchy? See code below for what I am trying to do.

import java.util.ArrayList;

interface A {}
interface B{}
interface AB extends A, B{}

class D <T extends A & B> {    //This works but this is a class
    T variable;
}

public class C {

    ArrayList<AB> myList1 = new ArrayList<AB>();  // compiles
    ArrayList<? extends AB> myList3 =  new ArrayList<AB>(); //compiles

   //The following does not compile.
   ArrayList<? extends A & B> myList4 =  new ArrayList<AB>();

    //This works but this is a method: 
    public static <T extends A & B> T someMethod(ArrayList<? extends T> list) {
        return null;
    }

}

Answers


Yes:

class C<T extends A & B> {
    ArrayList<T> field;

    public <T2 extends A & B> void method() {
        ArrayList<T2> localVar;
    }
}

It looks a bit odd that you have to define an alias for the generic "type" outside of the scope where you use it but it works. I find it's easiest to see with the method: T2 is never used in the method declaration. It's solely used inside of the method.

It's unfortunate that these inner type limits become part of the public API this way but that's the only way I know to make this work.

If you don't want this, then try an inner, private interface (AB) in your example.


Need Your Help

How to configure Jetty Handlers?

java jsp jetty handlers

I am encountering a problem with setting up the handlers for my web application, what I want is : Having some requests handled by an HTTPServlet with doGet and doPost methods ( how can I load JSP p...

Mule ESB, what version of XPath does it use

xml xpath mule esb

I can not tell from the documentation, what version of XPath does Mule use ?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.