【问题标题】:How can i sort objects in arrayList? [closed]如何对arrayList中的对象进行排序? [关闭]
【发布时间】:2018-03-25 20:41:36
【问题描述】:

我正在尝试对 arrayList 中的对象进行排序。可能就像节点和边缘。 例如:我有这样的对象:

Object2[B, C], Object1[A, B], Object4[E, F], Object3[C, D], 对象5[F, G],...

我的问题是如何将其分类为这样的组:

Object1[A, B], Object2[B, C], Object3[C, D] = Group1 Object4[E, F], Object5[F, G] = Group2 ...

我该怎么做?

【问题讨论】:

  • 实际上有几十种排序算法,当然每种算法都有多种语言的实现,而您找不到一个可以使用或适应您的使用?这表明您明显缺乏能力或努力,并且没有遵循 SO 的目的,即回答特定的编码问题。
  • 你可以实现Comparable,然后根据你的需要重写compareTo方法,然后调用Collections.sort(yourArrayList)方法。这只是其中一种方式...

标签: java sorting arraylist


【解决方案1】:

如下图使用ComparableComparator,您也可以访问https://www.journaldev.com/780/comparable-and-comparator-in-java-example了解更多详情。

    import java.util.Comparator;

    class Employee implements Comparable<Employee> {

        private int id;
        private String name;
        private int age;
        private long salary;

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        public int getAge() {
            return age;
        }

        public long getSalary() {
            return salary;
        }

        public Employee(int id, String name, int age, int salary) {
            this.id = id;
            this.name = name;
            this.age = age;
            this.salary = salary;
        }

        @Override
        public int compareTo(Employee emp) {
            //let's sort the employee based on id in ascending order
            //returns a negative integer, zero, or a positive integer as this employee id
            //is less than, equal to, or greater than the specified object.
            return (this.id - emp.id);
        }

        @Override
        //this is required to print the user friendly information about the Employee
        public String toString() {
            return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" +
                    this.salary + "]";
        }
}

Default Sorting of Employees list: [[id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000]]

【讨论】:

    猜你喜欢
    • 2017-03-15
    • 2013-01-06
    • 2015-12-27
    • 1970-01-01
    • 1970-01-01
    • 2019-11-24
    • 2015-12-17
    • 2012-04-26
    相关资源
    最近更新 更多