对LinkedList w.r.t进行排序Enum通过保留插入订单

时间:2018-04-13 06:24:20

标签: java sorting data-structures linked-list

我遵循Java Collection How to - Sort List on object fields enum constant values教程并提出以下实施

$('quickSearch').on('paste', function() {
  setTimeout(function() {
    $('quickSearch').keyup();
  }, 100);
});

输出

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;

/*from   w  w w.j  av a2 s.  c  o  m*/
enum Level {
    HIGH, MEDIUM, LOW;
}

class Person {
    private Level severity;
    private String name;

    public Person(Level severity, String name) {
        super();
        this.severity = severity;
        this.name = name;
    }

    public Level getSeverity() {
        return severity;
    }

    public void setSeverity(Level severity) {
        this.severity = severity;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class Main {
    public static void main(String[] args) {
        Person p8 = new Person(Level.LOW, "8");
        Person p9 = new Person(Level.HIGH, "9");
        Person p10 = new Person(Level.HIGH, "10");
        Person p11 = new Person(Level.LOW, "11");

        List<Person> persons = new LinkedList<Person>();
        persons.add(new Person(Level.HIGH, "1"));
        persons.add(new Person(Level.MEDIUM, "2"));
        persons.add(new Person(Level.LOW, "3"));
        persons.add(new Person(Level.HIGH, "4"));
        persons.add(new Person(Level.MEDIUM, "5"));
        persons.add(new Person(Level.LOW, "6"));
        persons.add(new Person(Level.LOW, "7"));

        sort(persons);

        for (Person person : persons) {
            System.out.println(person.getName() + " " + person.getSeverity());
        }

        System.out.println("\nAfter\n");

        persons.add(p8);
        persons.add(p9);
        persons.add(p10);
        persons.add(p11);

        sort(persons);

        for (Person person : persons) {
            System.out.println(person.getName() + " " + person.getSeverity());
        }
    }

    private static void sort(List<Person> persons) {
        Collections.sort(persons, new Comparator<Person>() {
            @Override
            public int compare(Person person1, Person person2) {
                if (person1.getSeverity() == person2.getSeverity()) {
                    return person1.getName().compareTo(person2.getName());
                } else {
                    return person1.getSeverity().compareTo(person2.getSeverity());
                }
            }
        });
    }
}

我想在排序列表中保留插入顺序,而不管列表的排序次数和添加新对象的次数。我想通过使用1 HIGH 4 HIGH 2 MEDIUM 5 MEDIUM 3 LOW 6 LOW 7 LOW After 1 HIGH 10 HIGH 4 HIGH 9 HIGH 2 MEDIUM 5 MEDIUM 11 LOW 3 LOW 6 LOW 7 LOW 8 LOW 我可以实现目标但失败了。

所需输出

LinkedList

有没有办法在排序/插入后保持插入顺序?

0 个答案:

没有答案