我已經試過這樣一個解決方案,它使用的ArrayList按您的要求:
首先,我已經爲你操作的新的數據結構。由於每個值將舉行兩次城市名稱:
public class Citizen implements Comparable<Citizen> {
private int citizenId;
private String subjectOne;
private String subjectTwo;
public Citizen(int rollNumber, String subjectOne, String subjectTwo){
this.citizenId = rollNumber;
this.subjectOne = subjectOne;
this.subjectTwo = subjectTwo;
}
public int getRollNumber() {
return citizenId;
}
public void setRollNumber(int rollNumber) {
this.citizenId = rollNumber;
}
public String getSubjectOne() {
return subjectOne;
}
public void setSubjectOne(String subjectOne) {
this.subjectOne = subjectOne;
}
public String getSubjectTwo() {
return subjectTwo;
}
public void setSubjectTwo(String subjectTwo) {
this.subjectTwo = subjectTwo;
}
public int compareTo(Citizen comparestu) {
int compareage=((Citizen)comparestu).getRollNumber();
/* For Ascending order*/
return this.citizenId-compareage;
/* For Descending order do like this */
//return compareage-this.studentage;
}
@Override
public String toString() {
return "[ rollno=" + citizenId + ", subjectOne=" + subjectOne + ", subjectTwo=" + subjectTwo + "]";
}
}
正如你可以在這裏看到比較的參數是使用實現可比接口作爲citizenID。
現在就撥打:
public static void main(String[] args) {
ArrayList<Citizen> studentList = new ArrayList<Citizen>();
studentList.add(new Citizen(25, "New York", "New Jersey"));
studentList.add(new Citizen(20, "Detroit", "Atlanta"));
studentList.add(new Citizen(50, "Chicago", "Los Angeles"));
studentList.add(new Citizen(30, "Kolkata", "Delhi"));
studentList.add(new Citizen(12, "Munmbai", "Baranasi"));
studentList.add(new Citizen(11, "Bangalore", "Goa"));
Collections.sort(studentList);
for(Citizen student: studentList){
System.out.println(student);
}
}
輸出:
[ rollno=11, subjectOne=Bangalore, subjectTwo=Goa]
[ rollno=12, subjectOne=Munmbai, subjectTwo=Baranasi]
[ rollno=20, subjectOne=Detroit, subjectTwo=Atlanta]
[ rollno=25, subjectOne=New York, subjectTwo=New Jersey]
[ rollno=30, subjectOne=Kolkata, subjectTwo=Delhi]
[ rollno=50, subjectOne=Chicago, subjectTwo=Los Angeles]
http://stackoverflow.com/questions/12824423/sort-array-and-reflect-the-changes-in-another-array?lq=1,http://stackoverflow.com/questions/112234/sorting -matched-arrays-in-java?lq = 1(與.NET不同,Java沒有標準庫支持多數組排序) – user2864740
每個數組中的值是否是唯一的? –
你可能更喜歡在java中使用Map來做類似的事情。 http://stackoverflow.com/questions/12824423/sort-array-and-reflect-the-changes-in-another-array?lq=1 http://stackoverflow.com/questions/109383/how-to -sort-A-映射鍵 - 值上的值 - 在-java的 – nullpointer