通配符:List<?> 意思是未知类型元素的List
|
1
2
3
4
5
6
7
|
public void test(List<?> c){ for(int i=0;i<c.size();i++) { System.out.println(c.get(i)); }} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public class RightTest{ static<T> void test(Collection<? extends T> from,Collection<T> to) { for(T ele:from) { to.add(ele); } } public static void main(String[] args) { List<Object> ao=new ArrayList<>(); List<String> as=new ArrayList<>(); test(as,ao); }} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
package test;import java.util.*;public class TreeSetTest { public static void main(String[] args) { TreeSet<String> ts1=new TreeSet<>( new Comparator<Object>() { public int compare(Object fst,Object snd) { return fst.hashCode()>snd.hashCode()? 1 :fst.hashCode()<snd.hashCode()? -1:0; } }); ts1.add("hello"); ts1.add("dao"); TreeSet<String> ts2=new TreeSet<>( new Comparator<String>() { public int compare(String first,String second) { return first.length()>second.length()? -1 :first.length()<second.length()? 1:0; } }); ts2.add("hello"); ts2.add("dao"); System.out.println(ts1); System.out.println(ts2); }} |
因为TreeSet(Comparator<? super E> c)
可以传入String或者String的父类Object
本文深入探讨了Java中泛型的使用方法,包括通配符的基本概念、通配符的上限和下限,以及如何在实际代码中应用这些概念。通过具体的代码示例,读者可以更好地理解如何利用泛型提高代码的灵活性和复用性。
1356

被折叠的 条评论
为什么被折叠?



