Java 通配符泛型例子

请看下面的代码,其中会发生错误的代码已经注释掉,并且写明了错误类型

总体来说,泛型通配符就是为了支持多态时父子类,接口扩展类之间的相互转换而生

 

[java] view plaincopyprint?
  1. package test;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. publicclass GenericTester {
  5. publicstaticvoid main(String[] args){
  6. GenericTester genericTester=new GenericTester();
  7. List<TestA> list=new ArrayList<GenericTester.TestA>();
  8. GenericTester.TestA tester=genericTester.new TestA();
  9. list.add(tester);
  10. TryGeneric1(list);
  11. TryGeneric2(list);
  12. // TryGeneric3(list); has compile error
  13. // TryGeneric4(list); has compile error
  14. }
  15. privateinterface ITest{
  16. publicvoid Test();
  17. }
  18. privateclass TestA implements ITest{
  19. @Override
  20. publicvoid Test() {
  21. // TODO Auto-generated method stub
  22. System.out.println("TestA");
  23. }
  24. }
  25. privatestaticvoid TryGeneric1(List<? extends ITest> testList){
  26. for(ITest tester:testList){
  27. tester.Test();
  28. }
  29. }
  30. privatestaticvoid TryGeneric2(List<?> testList){
  31. // for(ITest tester:testList) // cause error
  32. for(Object tester:testList){
  33. ((ITest)tester).Test();
  34. }
  35. }
  36. privatestaticvoid TryGeneric3(List<ITest> testList){
  37. for(ITest tester:testList){
  38. ((ITest)tester).Test();
  39. }
  40. }
  41. privatestaticvoid TryGeneric4(List<Object> testList){
  42. for(Object tester:testList){
  43. ((ITest)tester).Test();
  44. }
posted on 2012-11-07 17:48  wencansz  阅读(115)  评论(0编辑  收藏  举报