Java 通配符泛型例子
请看下面的代码,其中会发生错误的代码已经注释掉,并且写明了错误类型
总体来说,泛型通配符就是为了支持多态时父子类,接口扩展类之间的相互转换而生
- package test;
- import java.util.ArrayList;
- import java.util.List;
- publicclass GenericTester {
- publicstaticvoid main(String[] args){
- GenericTester genericTester=new GenericTester();
- List<TestA> list=new ArrayList<GenericTester.TestA>();
- GenericTester.TestA tester=genericTester.new TestA();
- list.add(tester);
- TryGeneric1(list);
- TryGeneric2(list);
- // TryGeneric3(list); has compile error
- // TryGeneric4(list); has compile error
- }
- privateinterface ITest{
- publicvoid Test();
- }
- privateclass TestA implements ITest{
- @Override
- publicvoid Test() {
- // TODO Auto-generated method stub
- System.out.println("TestA");
- }
- }
- privatestaticvoid TryGeneric1(List<? extends ITest> testList){
- for(ITest tester:testList){
- tester.Test();
- }
- }
- privatestaticvoid TryGeneric2(List<?> testList){
- // for(ITest tester:testList) // cause error
- for(Object tester:testList){
- ((ITest)tester).Test();
- }
- }
- privatestaticvoid TryGeneric3(List<ITest> testList){
- for(ITest tester:testList){
- ((ITest)tester).Test();
- }
- }
- privatestaticvoid TryGeneric4(List<Object> testList){
- for(Object tester:testList){
- ((ITest)tester).Test();
- }