Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何根据两个对象参数对对象的链接列表进行排序?_Java_Sorting_Linked List - Fatal编程技术网

Java 如何根据两个对象参数对对象的链接列表进行排序?

Java 如何根据两个对象参数对对象的链接列表进行排序?,java,sorting,linked-list,Java,Sorting,Linked List,我使用链表来表示一个稀疏矩阵,其中链表仅包含非零元素及其在矩阵中的行和列,以避免浪费内存 我需要能够根据这些元素的行和列按顺序显示它们的位置。例如,保存{data 5,row 2,col 0},{data 8,row 0,col 2},{data 1,row 0,col 1}的矩阵将打印出来: 01108205 矩阵的形式如下: LinkedList<MatrixElement> matrix = new LinkedList<MatrixElement>(); cla

我使用链表来表示一个稀疏矩阵,其中链表仅包含非零元素及其在矩阵中的行和列,以避免浪费内存

我需要能够根据这些元素的行和列按顺序显示它们的位置。例如,保存{data 5,row 2,col 0},{data 8,row 0,col 2},{data 1,row 0,col 1}的矩阵将打印出来:

01108205

矩阵的形式如下:

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));

您可能想考虑在<代码> MatRXEngult类中实现<代码>可比较的< /代码>接口。另外,值得考虑重写此类的

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;
    }
}
您得到的输出:

[[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]]

看一看嗨!jdk团队更改了排序算法,因此现在列表接口将列表的内容复制到一个数组中,对数组进行排序,并更改数组中每个节点的内容,这就是复杂性保持为O(nlogn)的原因
[[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]]