Home  >  Q&A  >  body text

问下这两个java的泛型方法的写法不一样, 但效果一样, 使用场景有何不同

定义

    public static void printList(List<?> list) {
        for (Object elem : list){
            System.out.println(elem + " ");
        }
    }

    public static <T> void printList2(List<T> list) {
        for (T elem : list){
            System.out.println(elem + " ");
        }
    }

使用

        MyList.printList(Arrays.asList(1, 2, 3));

        MyList.printList2(Arrays.asList(1, 2, 3));
怪我咯怪我咯2744 days ago580

reply all(4)I'll reply

  • 天蓬老师

    天蓬老师2017-04-18 10:50:45

    <?> can be written arbitrarily without restrictions,

    <T> requires that the places where T appears are of the same generic type

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 10:50:45

    The effect is the same, it does not mean that <T> requires that the places where T appears are of the same type. In fact, the above two methods are compiled into bytecode. List<T> and List<?> are both List<Object> at the bottom level.

    But the second usage does not play any role in actual development. Why, unless the generic is the type that declares the return value, or it is declared at the class level. For example

    private static <T> T fun1(List<T> list) {
    }

    or

    public interface Main<T> {
        public void fun(T t);
    }
    //然后
    
    public class MainImpl<String> {
        @override
        public void fun(String str) {
        }
    }

    This is what worked.

    Otherwise, use it like this public static <T> void fun1(List<T> list)
    What is the role of generics here? I really don't see what effect it has. It should be said that there is no need to use it this way.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:50:45

    ? Both T and T represent uncertain types, but using T can perform object operations, such as return <T>t; In this case, should T be used instead? .

    reply
    0
  • 黄舟

    黄舟2017-04-18 10:50:45

    List<?>List<T> 的超类,能使用 List<?> 的地方都可以使用 List<T>

    reply
    0
  • Cancelreply