Java Self-Regulatory Generics with Wildcards

Is it possible to indicate that an unknown general type is self-referential?

Failed to try:

import java.util.*;

class Generics {
   public enum A { A1, A2 }
   public enum B { B1, B2 }

   public static List<? extends Enum<?>> listFactory(String[] args) {
      if (args.length == 0) {
         return new ArrayList<A>(Arrays.asList(A.A1, A.A2));
      } else {
         return new ArrayList<B>(Arrays.asList(B.B1, B.B2));
      }
   }

   public static void main(String[] args) {
      List<? extends Enum<?>> lst = listFactory(args);
      dblList(lst);
      System.out.println(lst);
   }

   public static <EType extends Enum<EType>> void dblList(List<EType> lst) {
      int size = lst.size();
      for (int i = 0; i < size; i++) {
         lst.add(lst.get(i));
      }
   }
}

This results in a compilation error:

Generics.java:17: error: method dblList in class Generics cannot be applied to given types;
      dblList(lst);
      ^
  required: List<EType>
  found: List<CAP#1>
  reason: inferred type does not conform to declared bound(s)
    inferred: CAP#1
    bound(s): Enum<CAP#1>
  where EType is a type-variable:
    EType extends Enum<EType> declared in method <EType>dblList(List<EType>)
  where CAP#1 is a fresh type-variable:
    CAP#1 extends Enum<?> from capture of ? extends Enum<?>
1 error

Ideally, the return type listFactory()means that the list contains self-referencing generic types (whose exact type is unknown).

Is it possible? If so, what should be the types listFactory()and lst?

+4
source share
2 answers

Effective Java Item 28 prohibits the use of wildcards in return types:

. , , .

. , , , . , , - API .

, EJ. listFactory() List<Enum<?>>, , , , , , .

listFactory() :

public static List<Enum<?>> listFactory(String[] args)

dblList():

public static <E> void dblList(List<E> lst)
+1

Java , , . , ( ).

, , , , :

<E extends Enum<E>> List<E> listFactory(String[] args);

- .

- :

interface EnumList<E extends Enum<E>> extends List<E> {

}

EnumList<?> listFactory(String[] args);

:

EnumList<?> x = listFactory(args);
dblList(x);

dblList :

<E extends Enum<E>> void dblList(List<E> list);

, , , , . , dblList :

<E> void dblList(List<E> list);

.

0

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


All Articles