[英]Stuck trying to sort parallel arrays
I am trying to sort 2 parallel arrays one with a String
and one with int
s in it 我正在尝试对2个并行数组进行排序,其中一个数组包含一个String
,另一个数组包含int
。
I want to sort it by the int
s and then sort the String
to match I am using this code: 我想按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;
}
}
This has worked for me before when sorting and string and double array but now I am getting int cannot be dereferenced
error on the line if (calctemp[i].compareTo(calctemp[i + 1]) > 0)
I am guessing this is due to int
being a primitive but I cannot figure out what to replace it with to make it work. 这在排序和字符串和双if (calctemp[i].compareTo(calctemp[i + 1]) > 0)
数组之前为我工作,但是现在if (calctemp[i].compareTo(calctemp[i + 1]) > 0)
我int cannot be dereferenced
获取int cannot be dereferenced
错误,我猜这是由于int
是原始元素,但我无法弄清楚要用什么替换它才能使其工作。
Any help would be appreciated. 任何帮助,将不胜感激。
I think the error comes at calctemp[i].compareTo(calctemp[i + 1])
while calctemp[i]
is just an int and doesn't have the method compareTo
. 我认为错误来自calctemp[i].compareTo(calctemp[i + 1])
而calctemp[i]
只是一个int,没有方法compareTo
。
A quick fix would be to compare as primitives using >
as follows: 一个快速的解决方法是使用>
进行比较,如下所示:
if (calctemp[i] > calctemp[i + 1])
But in the long run, i would also do it as @MarcoAcierno suggested. 但是从长远来看,我也会按照@MarcoAcierno的建议去做。 Introduce a class which would contain both int
and String
representations of the respective values. 介绍一个将同时包含相应值的int
和String
表示形式的类。 Then implement a comparator, which would compare the int
versions as: 然后实现一个比较器,它将比较int
版本为:
public int compare(MyObject o1, MyObject o2) {
return o1.getIntValue() > o2.getIntValue();
}
Don't forget to implement implement Comparable interface in your class. 不要忘记在您的类中实现实现Comparable接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.