The Java™ Tutorials — Generics :Generic Methods 泛型方法

The Java™ Tutorials — Generics :Generic Methods 泛型方法

原文地址:https://docs.oracle.com/javase/tutorial/java/generics/methods.html

关键点

  • 定义格式:private <K,V> boolean compare(Pair<K,V> p1, Pair<K,V> p2)
  • 调用格式:Util.compare(p1,p2)

全文翻译

Generic methods are methods that introduce their own type parameters. This is similar to declaring a generic type, but the type parameter’s scope is limited to the method where it is declared. Static and non-static generic methods are allowed, as well as generic class constructors.

泛型方法是指具有自己类型参数的方法。这与声明泛型相似,但是类型参数的有效范围仅局限于方法所定义的地方。静态和非静态泛型方法以及泛型类构造器是合法的。

The syntax for a generic method includes a type parameter, inside angle brackets, and appears before the method’s return type. For static generic methods, the type parameter section must appear before the method’s return type.

泛型方法的语法包括带有尖括号的泛型参数,这个参数的位置在方法返回类型之前。对于静态泛型方法而言,泛型参数部分必须出现在方法返回类型的前面。

The Util class includes a generic method, compare, which compares two Pair objects:

这个Util类包含了一个泛型方法compare,它用于比较两个Pair对象:

public class Util {
public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) {
return p1.getKey().equals(p2.getKey()) &&
p1.getValue().equals(p2.getValue());
}
}

public class Pair<K, V> {

private K key;
private V value;

public Pair(K key, V value) {
this.key = key;
this.value = value;
}

public void setKey(K key) { this.key = key; }
public void setValue(V value) { this.value = value; }
public K getKey() { return key; }
public V getValue() { return value; }
}

The complete syntax for invoking this method would be:

调用此方法的完整语法格式为:

Pair<Integer, String> p1 = new Pair<>(1, "apple");
Pair<Integer, String> p2 = new Pair<>(2, "pear");
boolean same = Util.<Integer, String>compare(p1, p2);

The type has been explicitly provided, as shown in bold. Generally, this can be left out and the compiler will infer the type that is needed:

正如粗体显示的那样,类型以及被显示地提供了。总的来说,可以忽略这项工作,这个编译器将会推断出需要的类型:

Pair<Integer, String> p1 = new Pair<>(1, "apple");
Pair<Integer, String> p2 = new Pair<>(2, "pear");
boolean same = Util.compare(p1, p2);

This feature, known as type inference, allows you to invoke a generic method as an ordinary method, without specifying a type between angle brackets. This topic is further discussed in the following section, Type Inference.

这种特性名为类型推断。它允许你像调用一个常规方法那样调用泛型方法,且不需要再尖括号间指明一个类型。在下面的章节《类型引用》中,我们将对特性做更深刻的讨论。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值