我正在尝试根据另一个值数组(ms)更新(字面上排序)手动索引。
String ms[] = { "10","11","14","12"};
String indx[]={ "0", "1", "2", "3" }; // Manual index based on ms values`
String indx[]= { "0", "1", "3", "2"}; // After updating
String ms[] = { "10","11","14","12","13"};
String indx[]={ "0", "1", "3", "2" ,"4"};
String indx[]= { "0", "1", "4", "2" ,"3"};
如何在Java中实现这一目标。 我尝试过 TreeMap,Sort,Comparator impl 。但所有都给出了排序数组。
但是我需要更新索引而不是排序。
答案 0 :(得分:0)
您需要做的就是创建一个类,该类使用私有字段实现Comparable达毫秒和索引。将该类的任何实例放入某种排序数据结构(例如TreeSet)中,您就可以了。或者只是将实例添加到List并调用Collections.sort()。以下是带有工作示例的完整课程。
import java.util.Set;
import java.util.TreeSet;
public class Milli implements Comparable<Milli> {
private int ms, index;
public Milli (int ms, int index) {
this.ms = ms;
this.index = index;
}
@Override
public String toString () {
return Integer.toString(index);
}
@Override
public int compareTo (Milli o) {
return Integer.compare(ms, o.ms);
}
}
class Test {
public static void main (String[] args) {
Set<Milli> set = new TreeSet<>();
String ms[] = { "10","11","14","12"};
String indx[]={ "0", "1", "2", "3" }; // Manual index based on ms values
for (int i=0; i<ms.length; i++)
set.add(new Milli(Integer.parseInt(ms[i]), Integer.parseInt(indx[i])));
System.out.println(set);
}
}
答案 1 :(得分:0)
感谢大家的回答。不知何故,我通过使用以下代码实现了它。这可以按预期工作,但性能明智,我不确定。
请查看并发表评论。
long lastMsValue = Long.valueOf(ms[ms.length-1]);
int crntIndx = 65350; //Assuming not more than 1000 records.
if(ms.length == indx.length){
if(ms.length == 2 && Long.valueOf(ms[0]) > lastMsValue){
indx[0]="1";
indx[1]="0";
}else if(ms.length > 2){
for(int m=0;m<ms.length-1;m++){
if (Long.valueOf(ms[m]) > lastMsValue){
if(crntIndx > m)
crntIndx = m;
}else if(Long.valueOf(ms[m]) == lastMsValue){
crntIndx = m;
}
}
indx[indx.length-1] = String.valueOf(crntIndx);
System.out.println("Crnt Indx = " + crntIndx + " And Indx Array Value ");
for(int m=0;m<ms.length-1;m++){
if (Long.valueOf(ms[m]) > lastMsValue)
indx[m] = String.valueOf(Integer.valueOf(indx[m])+1);
}
}
}else{
System.out.println("Lengths are not equal and sorting is not done");
}