通配符、通配符上限、通配符下限

通配符: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));
    }
}
通配符上限:List<? extends Shape>    代表Shape或Shape的子類型
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);
    }
}
通配符下限:List<? super Type>   表示Type本身或者Type的父類
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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章