如何停止模型类中的自动订购字段?

时间:2018-12-31 09:44:31

标签: java android list sorting arraylist

我创建了一个模型类(此处仅显示构造函数)

public PieceModel(int position, int piece_id) {
    this.position = position;
    this.piece_id = piece_id;
}

然后添加一些数据

list.add(new PieceModel(1, 100));
list.add(new PieceModel(2, 300));
list.add(new PieceModel(3, 600));

然后我将列表转换为字符串,并按如下方式打印

[{"piece_id":100,"position":1},{"piece_id":300,"position":2},{"piece_id":600,"position":3}]

但是我需要这样

[{"position":1,"piece_id":100},{"position":2,"piece_id":200},{"position":3,"piece_id":300}]

请一些建议。

1 个答案:

答案 0 :(得分:4)

像这样?覆盖toString并重新排列属性?

static class PieceModel {
    private int position;
    private int piece_id;

    public PieceModel(int position, int piece_id) {
        this.position = position;
        this.piece_id = piece_id;
    }

    @Override
    public String toString() {
        return "{" +
                "position=" + position +
                ", piece_id=" + piece_id +
                '}';
    }
}

public static void main(String[] args) {
    List<PieceModel> list = new ArrayList<>();
    list.add(new PieceModel(1, 100));
    list.add(new PieceModel(2, 300));
    list.add(new PieceModel(3, 600));
    System.out.print(list.toString());
}

结果:

[{"position":1,"piece_id":100},{"position":2,"piece_id":200},{"position":3,"piece_id":300}]