问下这两个java的泛型方法的写法不一样, 但效果一样, 使用场景有何不同
怪我咯
怪我咯 2017-04-18 10:48:45
0
4
568

定义

    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));
怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(4)
Peter_Zhu

<?> can be written arbitrarily without restrictions,

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

伊谢尔伦

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.

Ty80

? 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? .

黄舟

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!