我有两个数组,其中一个数组代表一个名称集合,另一个数组描述它们的相关标记。我想按升序对数组内的标记进行排序,然后是与标记相关的相应名称。
我的目标是创建一个排名列表。我正在使用Processing来做这个
float sum = 0;
String [] name = {"A", "B", "C", "D","E"};
float [] mark = {12, 2, 4, 6, 23};
void setup() {
size(600, 600);
smooth();
}
void draw() {
background(225);
fill(0);
println(name.length);
for (int i =0; i<name.length; i++) {
text(name[i] + ":"+ mark[i], 100, 100+i*50);
}
}
/////// i wanted to sort it as E:23, A:12, D:6, C:4, B:2
如果有人可以帮助我,那就太好了。 :)
非常感谢, 优素福
答案 0 :(得分:1)
您可以创建一个实现Comparable
的数据持有者类。我想你也可以使用Map,就像hashMap一样。
这里是一个数据持有者类示例:
import java.util.Collections;
ArrayList <Data> d = new ArrayList<Data>();
void setup() {
size(600, 600);
d.add(new Data("A", 12));
d.add(new Data("B", 2));
d.add(new Data("C", 4));
d.add(new Data("D", 6));
d.add(new Data("E", 23));
println("before sorting:\n" + d);
//used reverseOrder as it goes decrescent, but you could just reverse
//the "natural" order in the class it self. Exchange -1 and 1 in compareTo()
// and use Collections.sort(d); here
Collections.sort(d, Collections.reverseOrder());
println("after sorting:\n" + d);
}
/////// i wanted to sort it as E:23, A:12, D:6, C:4, B:2
class Data implements Comparable {
String name;
int mark;
Data(String _n, int _m) {
name = _n;
mark = _m;
}
// this sets the 'natural' order of Data
@Override
int compareTo(Object o) {
Data other = (Data) o;
if (other.mark > mark) {
return -1;
} else if (other.mark < mark) {
return 1;
}
return 0;
}
// this to get a nice looking output in console...
@Override
String toString() {
return name + ":" + nf(mark, 2);
}
}