Java中的参数类型 [英] Type arguments in Java

查看:57
本文介绍了Java中的参数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个声明之间有区别吗?

Is there any difference between the following two declarations?

public<C extends Condition<E>> List<E> search (C condition)

public List<E> search (Condition<E> condition)

一个明显的区别是:在第一种情况下,可以在search的主体中使用C.但是假设C不会在search的正文中使用:仍然有什么区别吗?

One difference is obvious: in the first case C can be used in the body of search. But assumed that C would not be used in the body of search: is there still any difference?

推荐答案

不,没有有用的区别.可以将区别简化为以下内容.

No, there's no useful difference. The distinction could be simplified to the following.

<T> void m(T object)

void m(Object object)

尽管第一个可以调用this.<String>m(42)并且不会编译-但这没有任何价值.

Although with the first one could call this.<String>m(42) and it wouldn't compile - but there's no value to that.

泛型方法的值在其类型参数表示某种关系时出现,例如:

The value of a generic method comes when there is some relationship expressed by its type parameters, for example:

<T> T giveItBackToMe(T object) {
    return object;
}

...

String s = giveItBackToMe("asdf");
Integer i = giveItBackToMe(42);

或者:

<T> void listCopy(List<T> from, List<? super T> to) {
    to.addAll(from);
}

...

List<Integer> ints = Arrays.asList(1, 2, 3);
List<Number> nums = new ArrayList<>();
listCopy(ints, nums);

这篇关于Java中的参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆