![](/img/trans.png)
[英]How can I sort a list of Java objects based on parameters that a user selects from a drop down menu?
[英]How can I sort a linked list of objects based on two of the objects parameters?
我正在使用鏈表表示稀疏矩陣,其中鏈表僅將非零元素及其在矩陣中的行和列保存在一起,以免浪費內存。
我需要能夠根據它們的行然后列按順序顯示這些元素的位置。 例如,保存{數據5,行2,列0},{數據8,行0,列2},{數據1,行0,列1}的矩陣將打印出來:
0 1 1,0 2 8,2 0 5。
矩陣寫為:
LinkedList<MatrixElement> matrix = new LinkedList<MatrixElement>();
元素類寫為:
class MatrixElement { //Data object for each node in list, holds value and location
private int data;
private int row;
private int col;
public MatrixElement(int row, int col, int data){
this.data = data;
this.row = row;
this.col = col;
}
public int getData(){
return data;
}
public int getRow(){
return row;
}
public int getCol(){
return col;
任何有關我應如何對其進行排序以最終打印出來的反饋,我們將不勝感激。 謝謝您的幫助。
您可以按行然后按列進行排序,如下所示:
matrix.sort(Comparator.comparingInt(MatrixElement::getRow)
.thenComparingInt(MatrixElement::getCol));
您可能要考慮在MatrixElement
類中實現Comparable
接口。 另外,值得考慮重寫此類的toString()
方法,以使其以更易讀的方式打印結果。 看一下如何實現:
class MatrixElement implements Comparable<MatrixElement> {
//fields, constructor and getters...
public String toString() {
return "[row:" + this.getRow() + ", col:" + this.getCol() + ", data:" + this.getData() + "]";
}
@Override
public int compareTo(MatrixElement me) {
if(this.getRow() < me.getRow()) {
return -1;
} else if(this.getRow() > me.getRow()) {
return 1;
} // if getRow() is equal to both, proceed with comparing columns...
if(this.getCol() < me.getCol()) {
return -1;
} else if(this.getCol() > me.getCol()) {
return 1;
} // if getCol() is equal to both, it returns 0
return 0;
}
}
在實現compareTo()
方法之后,在使用Collections.sort()
方法時,將使用compareTo()
方法中提供的順序:
List<MatrixElement> elements = new ArrayList<>();
elements.add(new MatrixElement(5,2,0));
elements.add(new MatrixElement(8,0,2));
elements.add(new MatrixElement(1,0,1));
System.out.println(Arrays.toString(elements.toArray()));
Collections.sort(elements);
System.out.println(Arrays.toString(elements.toArray()));
您得到的輸出:
[[row:5, col:2, data:0], [row:8, col:0, data:2], [row:1, col:0, data:1]]
[[row:1, col:0, data:1], [row:5, col:2, data:0], [row:8, col:0, data:2]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.