코드 (전체 소스 코드)가 있습니다.
public class AutoConversionTest {
@Test
public void test_autoConversion() {
Wrapper wrapper = new Wrapper();
wrapper.setList(new ArrayList<Sub>());
wrapper.addAll(new ArrayList<Sub>());
}
class Wrapper {
List<? extends Super> list;
public void setList(List<? extends Super> list) {
this.list = list;
}
public void addAll(List<? extends Super> list) {
this.list.addAll(list); //TROUBLES!
}
}
class Super {}
class Sub extends Super {}
}
질문 : Wy 오류 및 해결 방법?
수정 됨 : 내 오류 로그
java: no suitable method found for `addAll(java.util.List<? extends expectations.public_method.experiments.AutoConversionTest.Super>)`
method `java.util.List.addAll(int,java.util.Collection<? extends expectations.public_method.experiments.AutoConversionTest.Super>)` is not applicable (actual and formal argument lists differ in length)
method `java.util.List.addAll(java.util.Collection<? extends expectations.public_method.experiments.AutoConversionTest.Super>)` is not applicable (actual argument `java.util.List<? extends expectations.public_method.experiments.AutoConversionTest.Super>` cannot be converted to `java.util.Collection<? extends expectations.public_method.experiments.AutoConversionTest.Super>` by method invocation conversion)
Sub 클래스가 Super 클래스를 다음과 같이 확장하기를 원한다고 추론합니다.
class Super {}
class Sub extends Super {}
위와 같이 클래스를 작성하더라도 와일드 카드는 읽기 전용 목록에만 사용되므로 목록에 아무것도 추가 할 수 없습니다. Wrapper 클래스를 사용하여 다음과 같이 작업을 수행 할 수 있습니다.
public class Wrapper<T extends Super> {
private List<T> list = new ArrayList<T>();
void doStuff(){
List<Sub> al = new ArrayList<Sub>();
for(Sub s : al)
list.add((T) s);
}
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다