java - 寻找通用ArrayList中的最小值

标签 java generics arraylist max min

我不断收到一条消息,告诉我运算符(operator) <类型 T,T 未定义。这发生在周围

if(index<lowest)

我将如何修改我的程序,以便可以使用通用方法获取数组列表的最小值和最大值?

package p07;

import java.util.ArrayList;

public class MyList<T extends Number> {
    private ArrayList<T> l;

    public MyList(ArrayList<T> l) {
        this.l=l;
    }
    public void add(T x) {
        l.add(x);
    }
    public static <T> void smallest(ArrayList<T> l) {
        T lowest=l.get(0);
        for(T index:l) {
            if(index<lowest) { 

            }
        }   
    }
}

最佳答案

编译器是正确的:运算符<仅适用于原始数字类型。引用section 15.20.1 JLS 的:

The type of each of the operands of a numerical comparison operator must be a type that is convertible (§5.1.8) to a primitive numeric type, or a compile-time error occurs.

因此,它不是为对象定义的,甚至不是为数字定义的,因为它们无法拆箱为原始类型:section 5.1.8 JLS 的:

A type is said to be convertible to a numeric type if it is a numeric type (§4.2), or it is a reference type that may be converted to a numeric type by unboxing conversion.

您需要的是使用 Comparator 或制作您的对象 Comparable Comparator s 负责比较相同类型的两个对象。由于这里的对象是数字,而不是 Comparable ,您需要使用自定义Comparator ,像这样:

Comparator<Number> myComparator = new Comparator<Number>() {
    @Override
    public int compareTo(Number n1, Number n2) {
        // implement logic here.
        // Return -1 if n1 < n2, 0 if n1 = n2, 1 if n1 > n2
    }
};

然后你可以像这样使用这个比较器:

public static <T extends Number> T smallest(List<T> l) {
    T lowest = l.get(0);
    for (T index : l) {
        if (myComparator.compareTo(index, lowest) < 0) { 
            index = lowest;
        }
    }
    return lowest;
}

(请注意,我将 T extends Number 添加到方法的类型中 - 这是因为该方法是静态的,因此它实际上声明了该类所属的另一种类型 T

关于java - 寻找通用ArrayList中的最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33068175/

相关文章:

java - 在 REST API 中使用受检异常与未受检异常

java - 将 Object 转换为泛型类型时未引发无效的 ClassCast 异常

c# - 从对象列表中删除重复项

java - java中给定键随机访问映射条目

java - 制作包含对象(椭圆形、矩形等)的 ArrayList

java - 如何自动增加字符串/整数以提高效率?

java - 更新响应对象而不转换为java对象

java - 摩擦正则表达式 : matching a char except when after by another char

java - 有没有办法让这个代码片段更有效率?

Java 将特定类的列表添加到 java.lang.Object 的列表与 java 8 流一起工作 - 为什么?