gpt4 book ai didi

java - 坚持尝试对并行数组进行排序

转载 作者:行者123 更新时间:2023-11-29 08:50:21 25 4
gpt4 key购买 nike

我正在尝试对 2 个并行数组进行排序,一个是 String,另一个是 int

我想按 int 对它进行排序,然后对 String 进行排序以匹配我正在使用的代码:

        for (int t = 0; t < calctemp.length - 1; t++) {
for (i = 0; i < calctemp.length - 1; i++) {
if (calctemp[i].compareTo(calctemp[i + 1]) > 0) {
tmpStr = stringtemp[i];
tmpInt = calctemp[i];
stringtemp[i] = stringtemp[i + 1];
calctemp[i] = calctemp[i + 1];
stringtemp[i + 1] = tmpStr;
calctemp[i + 1] = tmpInt;
}
}

这在排序和字符串和双数组之前对我有用,但现在我在 if (calctemp[i].compareTo(calctemp[我 + 1]) > 0)我猜这是因为 int 是原始类型,但我无法弄清楚用什么替换它才能使其正常工作。

如有任何帮助,我们将不胜感激。

最佳答案

我认为错误出现在 calctemp[i].compareTo(calctemp[i + 1])calctemp[i] 只是一个 int 而不是有方法 compareTo

一个快速的修复方法是使用 > 将其作为基元进行比较,如下所示:

if (calctemp[i] > calctemp[i + 1])

但从长远来看,我也会按照@MarcoAcierno 的建议去做。引入一个包含相应值的 intString 表示的类。然后实现一个比较器,它将 int 版本比较为:

public int compare(MyObject o1, MyObject o2) {
return o1.getIntValue() > o2.getIntValue();
}

不要忘记在你的类中实现 implement Comparable 接口(interface)。

关于java - 坚持尝试对并行数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23047925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com