A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© yanghu 中级黑马   /  2014-6-13 21:14  /  884 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. public class Test2 {
  2.         public static <T> void show(Set<T> a, Set<T> b){
  3.                 System.out.println(b.getClass().getName());
  4.         }
  5.         public static void main(String[] args) {
  6.                 Set<String> a = new HashSet<String>();
  7.                 Set<Integer> b = new HashSet<Integer>();
  8.                 /*String a = new String("asda");
  9.                 Integer b = new Integer(12); */
  10.                 Test2.show(a, b);
  11.         }
  12. }
复制代码


为什么调用Test2.show(a, b)编译会出错,求解答,谢谢。

3 个回复

倒序浏览
因为a,b的类型不一致啊!
回复 使用道具 举报
  • public class Test2 {
  •         public static <T> void show(Set<T> a, Set<T> b){
  •                 System.out.println(b.getClass().getName());
  •         }
  •         public static void main(String[] args) {
  •                 Set<String> a = new HashSet<String>();
  •                 Set<Integer> b = new HashSet<Integer>();
  •                 /*String a = new String("asda");
  •                 Integer b = new Integer(12); */
  •                 Test2.show(a, b);
  •         }
  • }
  • 上面是你的代码:
  • 我的理解是静态方法的泛型声明为<T>,静态show()方法的参数列表的泛型也是<T>,正常逻辑是传入的两个Set集合的参数化类型是可以不同的(只是都叫T而已),
  • 但是静态方法的泛型声明会让编译器认为你传入的是集合参数化类型是同一中类型!,所以会报错!
  • 上面纯属个人理解:多指教

回复 使用道具 举报
public class GenericDemo {

        public static void main(String[] args) {
                 Set<String> a = new HashSet<String>();
                 Set<String> a1 = new HashSet<String>();
         Set<Integer> b = new HashSet<Integer>();
         /*String a = new String("asda");
         Integer b = new Integer(12); */
         show(a, b);

        }
        public static void show(Set<?> a, Set<?> b){
        System.out.println(a.getClass().getName());
        System.out.println(b.getClass().getName());
}
}       
我觉得这样写就了没什么问题了!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马