通配符: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