使用泛型创建返回较大值的 max 函数

发布于 2024-09-11 20:20:48 字数 579 浏览 2 评论 0 原文

在 Java 中,我将如何使用泛型创建一个 max 函数,该函数将两个相同类型的 Comparable 对象作为参数并返回较大的一个?

我尝试过:(

public static <T extends Comparable> T max(T obj1, T obj2)
{
    return ( ((obj1).compareTo(obj2) >= 0) ? obj1 : obj2);
}

如果它们相等,则返回 obj1。)

该方法基于我在 http://www.informit.com/articles/article.aspx?p=170176&seqNum=3

但是,当我编译它时,我收到此警告(使用 -Xlint:unchecked 编译): 警告:[未检查] 未检查地调用compareTo(T)作为原始类型java.lang.Comparable的成员

In Java, how would I use generics to create a max function that takes as parameters two Comparable objects of the same type and returns the larger one?

I tried:

public static <T extends Comparable> T max(T obj1, T obj2)
{
    return ( ((obj1).compareTo(obj2) >= 0) ? obj1 : obj2);
}

(It returns obj1 if they are both equal.)

The method is based on code I found at http://www.informit.com/articles/article.aspx?p=170176&seqNum=3.

However, when I compile it I get this warning (compiling with -Xlint:unchecked):
warning: [unchecked] unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

忆梦 2024-09-18 20:20:48

发生这种情况是因为您使用原始类型 Comparable,并且编译器无法确定您要比较的对象,因为compareTo 使用 Comparable 的类型参数。您还需要参数化 Comparable:

public static <T extends Comparable<? super T>> T max(T obj1, T obj2)

您需要使用 ? super T 因为您可能有一个类 A,它扩展了一个实现 Comparable 的类 B,但 A 没有实现 Comparable。那么你最多可以传递两个 A 对象,并且 B 匹配 吗? super A,因此即使对于 A 对象,您也可以调用 B 中定义的 compareTo 方法。如果您使用 > 并尝试传递两个 A 对象,编译器会抱怨它们没有实现 Comparable,即使它们从 B 继承了 compareTo 方法。

That happens because you use the raw type Comparable, and the compiler can't be sure what you're comparing against, since compareTo uses the type parameter of Comparable. You need to parametrize Comparable as well:

public static <T extends Comparable<? super T>> T max(T obj1, T obj2)

You need to use ? super T since you may have a class A that extends a class B which implements Comparable<B>, but A doesn't implement Comparable<A>. So then you can pass max two A objects, and B matches ? super A, so you can call the compareTo method defined in B even for A objects. If you would use <T extends Comparable<T>> and tried to pass two A objects the compile would complain that they don't implement Comparable<A>, even though they inherit a compareTo method from B.

独行侠 2024-09-18 20:20:48

看看Guava的Ordering类的方法max Ordering.max(a, b)

Take a look at Guava's Method max Of Ordering Class Ordering.max(a, b).

风轻花落早 2024-09-18 20:20:48

public static > 将删除警告。

public static <T extends Comparable<T>> will remove warning.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文