【发布时间】:2016-09-23 10:19:42
【问题描述】:
很难让它变得有趣,因为一旦使用比较器排序的列表无法再次排序,但这是我们需要更改数组值来排序为波纹管
//ALL 应该总是在 TOP
- //如果取 1,则 //SortTech 的 mainList 进行排序 ALL , B , A , C, D, E, F ,G
- //1 被采取现在 4 被采取然后 //待排序的SortTech的mainList ALL, B , E, A , C, D, F ,G
- //现在 1,4 被丢弃,6,5 被取走然后 //SortTech 的 mainList 将被排序 ALL, G, F, A , B, C, D, E
- // 6,5 现在取 -1 然后 //SortTech 的主列表要排序 ALL, A , B, C, D, E , F, G
package com.test;
import java.util.ArrayList;
import java.util.List;
public class SortTech {
private long id;
private String name ;
public static void main(String[] args) {
List<SortTech> mainList = new ArrayList<>();
SortTech S1 = new SortTech();
S1.setName("ALL");
S1.setId(-1);
mainList.add(S1);
SortTech S2 = new SortTech();
S2.setName("A");
S2.setId(0);
mainList.add(S2);
SortTech S3 = new SortTech();
S3.setName("B");
S3.setId(1);
mainList.add(S3);
SortTech S4 = new SortTech();
S4.setName("C");
S4.setId(2);
mainList.add(S4);
SortTech S5 = new SortTech();
S5.setName("D");
S5.setId(3);
mainList.add(S5);
SortTech S6 = new SortTech();
S6.setName("E");
S6.setId(4);
mainList.add(S6);
SortTech S7 = new SortTech();
S7.setName("F");
S7.setId(5);
mainList.add(S7);
SortTech S8 = new SortTech();
S8.setName("G");
S8.setId(6);
mainList.add(S8);
/* //tried with comparator but it give unmodifiable list in return so could not modify any further
* Collections.sort(mainList, new Comparator<SortTech>() {
public int compare(SortTech t1, SortTech t2) {
if (t1.getName().equals("ALL"))
return -1;
if (t2.getName().equals("ALL"))
return 1;
return t2.getName().compareTo(t2.getName());
}
});*/
//ALL should always on TOP
//if 1 is taken
Long[] taken = new Long[]{(long) 1};
//mainList of SortTech to be sorted as ALL , B , A , C, D, E, F ,G
//system out
//1 was taken now 4 is taken
taken = new Long[]{(long) 1, (long) (4)};
//mainList of SortTech to be sorted as ALL, B , E, A , C, D, F ,G
//system out
//now 1,4 are dropped and 6,5 taken
taken = new Long[]{(long) 6, (long) (5)};
//mainList of SortTech to be sorted as ALL, G, F, A , B, C, D, E
//system out
//now 6,5 was taken now -1 is taken
taken = new Long[]{(long) 6, (long) (5), (long) (-1)};
//mainList of SortTech to be sorted as ALL, A , B, C, D, E , F, G
//system out
}
/**
* @return the id
*/
public long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
}
【问题讨论】:
-
旁注,您始终可以将字母表写入数组或字符串,并使用与 id 匹配的索引访问每个字符。
char[] alphabet = new char[]{'A', 'B', 'C', 'D', 'E'...};for(int i = 0; i < alphabet.length; i++){SortTech s = new SortTech();S.setName(alphabet[i]);S.setId(i);mainList.add(s);} -
@Underbalanced 感谢您的回复,A,B,C 和 0,1,2 只是示例,可以是苹果、谷歌或 323,456 之类的任何东西,这里我们也一定要采用长数组和基于长数组值,我们需要对对象列表进行排序
标签: java arrays list sorting arraylist