Java Generics creates an object list that extends class A and implements interface B

Consider this scenario

public abstract class A{

}

public interface B{

}

How to create a list of objects that extend A and implement B?

List<? extends A implements B> list = new List();

thank

+4
source share
2 answers

As I know, this is not supported using wildcard generics. This can be done using generated types.

public abstract class A{}
public interface B{}

public class Match extends A implements B{}
public class NotMatch1 implements B{}
public class NotMatch2 extends A{}

public class MyChecketList<T extends A&B> extends ArrayList<T>{}

public void use(){
    List<Match> a = new MyChecketList<>();//valid
    List<NotMatch1> b = new MyChecketList<>();//compiler error
    List<NotMatch2> c = new MyChecketList<>();//compiler error

    MyChecketList<Match> d = new MyChecketList<>();//valid
    MyChecketList<NotMatch1> e = new MyChecketList<>();//compiler error
    MyChecketList<NotMatch2> f = new MyChecketList<>();//compiler error
}
0
source

You can also use the '&' operator and declare an unknown class as a type parameter, as shown below. The advantage of this vs declaration class XXX extends B implement Ais that your code will work with any class that satisfies the limitations of not only XXXdescendants.

import java.util.*;

interface A {};

class B {};

class Test {

    public <T extends B & A> List<T> asList(Collection<T> elements) {
        List<T> result = new ArrayList<>(elements.size());
        for (T element : elements) result.add(element);
        return result;
    }
}
0
source

Source: https://habr.com/ru/post/1689756/


All Articles