62,616
社区成员
发帖
与我相关
我的任务
分享
void test(List<?> list){}
List list = new ArrayList(); list.add(1); swap(list);
//Consider the following method, printList:
public static void printList(List<Object> list) {
for (Object elem : list)
System.out.println(elem + " ");
System.out.println();
}
//The goal of printList is to print a list of any type, but it fails to achieve that goal — it prints only a list of Object instances; it cannot print List<Integer>, List<String>, List<Double>, and so on, because they are not subtypes of List<Object>. To write a generic printList method, use List<?>:
public static void printList(List<?> list) {
for (Object elem: list)
System.out.print(elem + " ");
System.out.println();
}
//Because for any concrete type A, List<A> is a subtype of List<?>, you can use printList to print a list of any type:
List<Integer> li = Arrays.asList(1, 2, 3);
List<String> ls = Arrays.asList("one", "two", "three");
printList(li);
printList(ls);//这样的话,如果调用List<Object>那个方法确实不行,但是为什么不用List<E>呢?
//----------------我的代码
public static <E> void printList(List<E> list) {
for (Object elem: list)
System.out.print(elem + " ");
System.out.println();
}
//这样的话,上面的结果也是可以打的
[/quote]List<?> 可以接收不定类型返回值,并且输出,例如:
public List<?> getRecListByDate(String loginName,Date dateStart,Date dateEnd,String Type) {
StringBuffer buffer = new StringBuffer();
buffer.append("select ");
buffer.append(Type);
buffer.append(" from tb_record where date >= :p1 and date <= :p2 and username = :p3 order by id");
Query query = createSqlQuery(buffer.toString(), new Parameter(dateStart,dateEnd,loginName));
return query.list();
//接收
List<?> records1 = new ArrayList<Double>();
records1 = getRecListByDate(token.getUsername(), formatDate.StringToDate(startDate), formatDate.StringToDate(endDate),Type);
前面的查询结果类型并不确定,接收是类型也是不确定的,这时候用List<?>可以接收到void printCollection(Collection<?> c) {
for (Object e : c) {
System.out.println(e);
}
}
但又可以被E代替,貌似唯一性职能没有体现出来
// 应该加上泛型声明
public static <E> String classify(List<E> lst){
return "List";
}
区别很细微……
首先第一个 List<?> 是只读的,如果你试图在方法内调用 lst.add(),只要不是 add(null) 都不能通过编译;
第二个可以用强转的方式add(),虽然可能会破坏类型安全。
然后第二个方法是泛型方法,你在调用的时候可以指定具体类型,这个具体类型可以作为返回类型使用:
public static <E> E classify(List<E> lst){
return "List";
}
// user code:
String s = ClassName.<String>classify(Arrays.asList("1","2","3"));
Integer i = ClassName.<Integer>classify(Arrays.asList(1, 2, 3));
public static String classify(List<?> lst){
return "List";
}
public static String classify(List<E> lst){
return "List";
}