Java 와일드카드 소개
                                            
                                                
                                                
                                                
                                                
                                                
                                                 9264 단어  java
                    
소개
와일드카드 표시(
? )는 프로그램을 보다 명시적으로 작성하는 데 도움이 될 수 있습니다.알 수 없는 유형을 나타내는 데 사용되며 제네릭 메소드 호출, 제네릭 클래스 인스턴스 생성 또는 상위 유형에 대한 유형 인수로 사용되지 않습니다.
예시
객체 계층 구조가 있다고 가정해 보겠습니다.
Animal 클래스는 Object에서 사소하게 Dog 및 Cat 클래스는 모두 Animal에서 상속합니다.GoldenRetriever 클래스는 Dog에서 상속합니다.
일반적으로 와일드카드를 사용하는 방법에는 세 가지가 있습니다.
void fun(List<? extends Animal> list)이 입력 목록은 최대 유형Animal에 대해 매개변수화됩니다(Animal의 하위 유형일 수 있음).
 void fun(List<? super Animal> list)이 입력 목록은 최소한 Animal 유형에 대해 매개변수화됩니다(Animal의 상위 유형이 될 수 있음).
 무제한:
void fun(List<?> list) { list.clear(); }clear()가 유형에 따라 달라지지 않기 때문에 목록의 유형이 무엇인지 상관하지 않습니다. Object 에 정의된 메서드만 사용해야 하는 경우 무제한 와일드카드가 제대로 작동합니다. 자바 데모 코드
See the following code,
WildcardDemo.java, for better understanding.
먼저
javac WildcardDemo.java로 컴파일을 시도하고 오류 콘솔을 확인하세요 :)둘째, 코드를 성공적으로 컴파일하려면
// X (can't compiled) 로 표시된 두 줄에 주석을 달아 코드를 컴파일해야 합니다.코드는 완전히 주석 처리됩니다. 이해가 안 되시면 댓글 남겨주세요.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
 * Our Object Hierarchy:
 *
 *          Object
 *            |
 *          Animal
 *           / \
 *        Dog   Cat
 *         |
 *  GoldenRetriever
 */
public class WildcardDemo {
  private class Animal {}
  private class Dog extends Animal {}
  private class Cat extends Animal {}
  private class GoldenRetriever extends Dog {}
  // `animals` is parameterized over "at most" type `Animal`
  private void funExtends(List<? extends Animal> animals) {
    // Can't add a Dog (subtype) to the `animals` because it may
    // contain something "lower than an Animal".
    // For example, it might be `List<GoldenRetriever>` or `List<Cat>`
    animals.add(new Dog()); // X (can't compiled)
    // Can't put anything into a type declared with an extends
    // wildcard except for the value `null`, which is a subtype
    // of every reference type
    animals.add(null);
    // Can retrieve an `Animal`, because any subtype of `Animal`
    // must be an `Animal`
    Animal animal = animals.get(0);
    System.out.println(animal.getClass().toString());
  }
  // `animals` is parameterized over "at least" type `Animal`
  private void funSuper(List<? super Animal> animals) {
    // Can add a `Dog` (subtype) to the `animals` because a `Dog`
    // is guaranteed an `Animal` or any supertype of an `Animal`
    animals.add(new Dog());
    // Can't get anything out from a type declared with a super
    // wildcard except for a value of type `Object`, which is a
    // super type of every reference type
    Animal animal = animals.get(0); // X (can't compiled)
    Object object = animals.get(1);
    System.out.println(object.getClass().toString());
  }
  private List<Animal> getAnimals() {
    return new ArrayList<>(Arrays.asList(
        new GoldenRetriever(),
        new Cat()
      )
    );
  }
  public static void main(String[] args) {
    WildcardDemo demo = new WildcardDemo();
    List<Animal> animals = demo.getAnimals();
    demo.funExtends(animals);
    demo.funSuper(animals);
  }
}
                Reference
이 문제에 관하여(Java 와일드카드 소개), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/walkccc/java-wildcards-demo-554f텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
                                
                                
                                
                                
                                
                                우수한 개발자 콘텐츠 발견에 전념
                                (Collection and Share based on the CC Protocol.)