简体   繁体   English

实现可比较接口的类型的 LinkedList

[英]LinkedList of type that implements the comparable interface

I'm looking for how to pass as a parameter of a method a linkedList of a type which implements the Comparable interface.我正在寻找如何将实现 Comparable 接口的类型的linkedList 作为方法的参数传递。

 public static void mergeSort(LinkedList<Comparable> list){}

I tried that but when I pass a primitive type such as Integer as a parameter it doesn't work.我试过了,但是当我将诸如 Integer 之类的原始类型作为参数传递时,它不起作用。 If someone have an idea?如果有人有想法?

You need to specify a bound parameter:您需要指定一个绑定参数:

  public static <T extends Comparable<? super T>> void mergeSort(LinkedList<T> list){}

This is taken from the method sort .这取自方法sort

Simply let the compiler know that the input type T extends Comparable<T> .只需让编译器知道输入类型T扩展Comparable<T>

public static <T extends Comparable<T>> void mergeSort(final LinkedList<T> list)

I would not use the ?我不会使用? , which is a wildcard and represents an unknown type . ,这是一个通配符,代表一个未知类型
Explicitly specifying the generic type is always better (see this question ).明确指定泛型类型总是更好(参见这个问题)。

Define a type parameter, and use that type parameter as the element type:定义一个类型参数,并将该类型参数用作元素类型:

public static <C extends Comparable<? super C>> void mergeSort(LinkedList<C> list){}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM