按字段和值的大小对类进行排序

时间:2013-08-12 05:28:53

标签: java class sorting

早上好。我有类,其中包含以下格式的数据:[int] [Object]。我从未使用过类,我通常使用Lists,Maps,现在我不明白如何在常见的类中实现它。如何按类中的字段排序?  小心,我的toString只显示没有字段编号的字段代码。

     I would like to sort this class by size of value[Object]
( "1 1234", "2 35881", ... "7 22" --> "7 22", "1 1234", "2 35881")



        public class Record {
            private int number;
            private Object code;

         ... Getters/Setters 

        @Override
        public String toString() {
            return (String)(this.code);
        }

        }


        public class Storage
        {
            List<Record> record;
            public Storage(){

                this.record = new ArrayList<Record>();

            }

            public void addRecord(Record record) {
                this.record.add(record);
            }
            public Record getRecord(int number){
                return this.record.get(number);
            }
            public void delRecord(int number){
                this.record.remove(number);
            }

            public Integer sizeStorage(){
                return record.size();
            }

        }

    public class Start {
        public static void main(String[] args) {

    System.out.println("Start reading from Xls");
    ReaderXls read = new ReaderXls();

    Storage storageRZS =  readrzs.ReadXls("Text1obj",2,12);

    .....
            System.out.println(storageRZS.getRecord(5));
            System.out.println(storageRZS.getRecord(7));
            System.out.println(storageRZS.getRecord(10));

    2122
    189266
    244

The result should be this:
        244
        2122
        189266

3 个答案:

答案 0 :(得分:3)

如果您希望以有序方式访问记录,则需要在记录类中使用comparator或实施comparable

样品:

 Collections.sort(listOfRecords, new Comparator<Record>() {
            @Override
            public int compare(Record o1, Record o2) {
                //null checks

                /*Compare the object field according to your custom logic. 
                 Here it is assumed that getObjectCodeAsInt() will return an integer equivalent of the objectCode.*/
                if(o1.getObjectCodeAsInt() > o2.getObjectCodeAsInt())
                    return 1;
                else if(o1.getObjectCodeAsInt() < o2.getObjectCodeAsInt())
                    return -1;

                return 0;
            }
        });

答案 1 :(得分:1)

您需要为客户Comparator提供同样的服务。阅读how to sort user defined objects

答案 2 :(得分:1)

我不确定这个问题的确切性。 但是,如果您希望按照不同的类属性(如您所说的字段)对列表进行排序(例如列表),则可以查看Collections.sort

您需要为每个排序属性实现Comparator接口。

此致 VJ