如何从链接列表中的位置上下移动项目?
文本文件包含保存在链表中的如下数据。我想根据第一项对物品进行分类,即TY12354,ytpy217,TY12354dsaf ....
TY12354,丰田,TY1257,2100000 SK2344,斯柯达,SO2345,180000 ytpy217,safsadf,asfasf,1241234 TY12354d,sfasdf,asfasf,235123412 TY12354dsaf,asdffasd,asfasfafsd,12344 ABC123,asdffasd,asfasfafsd,12344
我使用以下代码进行排序,但它不起作用:
for (int x = 0;x < (lstCar.size()-1); x++) {
c=(Car) lstCar.get(x); //lstCar is the linked list
d = (Car) lstCar.get(x+1);
int compare =d.getRegNumber().compareTo(c.getRegNumber()) ;
if(compare < 0){
temp = d;
lstCar(x)=c; //tried this method but it doesnt work
//lstCar.sort();
c = temp;
}
}
答案 0 :(得分:2)
Java已经有了一个功能: http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#sort%28java.util.List,%20java.util.Comparator%29
答案 1 :(得分:2)
这不是在LinkedList中设置元素的正确方法:
lstCar(x)=c; //tried this method but it doesnt work
改为使用:
lstCar.set(x,c);
如果你想通过保持这种方法对你的列表进行排序(即通过自己如图所示),那么方法.set(index,element)将适合你。