java通配符参数,区别? (通配符)和Java中的类型参数

Can somebody explain me what the difference is between these two methods? Are they same? They do look same to me in terms of what they solve. If they are same, why need ??

Method #1, Unbounded

public static void printList(List> list) {

for (Object elem : list)

System.out.println(elem + " ");

System.out.println();

}

Method #2, Unbounded:

public static void printList(List list) {

for (Object elem : list)

System.out.println(elem + " ");

System.out.println();

}

Method #1, Bounded

public static void printList(List extends Number> list) {

for (Object elem : list)

System.out.println(elem + " ");

System.out.println();

}

Method #2, Bounded:

public static void printList(List list) {

for (Object elem : list)

System.out.println(elem + " ");

System.out.println();

}

解决方案

They are the same in that they accept the same parameter types.

However, identifying the type with T (or whatever) lets you refer to the type elsewhere.

Edit: Examples:

Your unbounded examples do not make full use of the capabilities of parameterized types. You have:

public static void printList(List list) {

for (Object elem : list)

System.out.println(elem + " ");

System.out.println();

}

And that's sufficient for that example of printing string representations, but consider this (very contrived, and no error handling):

public static T getSecondItem (List list) {

T item = list.get(1);

return item;

}

The return type is T, which allows you to safely do things like this, with compile time type-checking:

class MyClass {

public void myMethod () { }

}

void somewhere () {

List items = ...;

getSecondItem(items).myMethod();

}

A named type also lets you share the same type constraint in multiple places, e.g.:

public int compareLists (List a, List b) {

...

}

If you did not name the type, you could not specify the constraint that a and b are the same list type (you could use List extends T> for more flexibility).

You also asked "Why do I need ??". The real answer is: You don't. It's mostly for aesthetics, I suppose. Java strives to be a precise and clutter-free language. There are many situations where you simply don't care what type you are referring to. In those cases, you may use ? without cluttering code with unused type parameter declarations.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值