4

I have an object with the following memebers:

class XNode {
    // key
    long magicNumber;   

    // metadata:
    int x;
    iny y;
    int z;
    double angle;
    double tempreture;
}

I want to use order list (the key is magicNumber).

Is there a list in java which already implements the add/remove/update in a order manner ? (I dont want to use Collections.sort for every operation).

Azil
  • 457
  • 2
  • 5
  • 10
  • ArrayList or LinkedList if duplication is allowed ? – Kick Buttowski May 29 '15 at 01:14
  • Short answer, not really, long answer, `TreeSet` "might" help and [this](http://stackoverflow.com/questions/8725387/why-is-there-no-sortedlist-in-java) might shed some more light on it – MadProgrammer May 29 '15 at 01:14
  • 2
    Do you need to allow duplicates? – Elliott Frisch May 29 '15 at 01:14
  • 1
    no duplicates are allowed – Azil May 29 '15 at 01:20
  • 2
    If you do not need support for duplicates, then `TreeSet` will allow you to iterate in sorted order. However, it doesn't support random access (e.g., the `i`-th element). So whether it will work for you depends on your requirements. You might also take a look at the new [`SortedList`](https://docs.oracle.com/javase/8/javafx/api/javafx/collections/transformation/SortedList.html) of Java FX. – Ted Hopp May 29 '15 at 01:23

3 Answers3

3

no duplicates are allowed

First, in XNode there is a typo. I believe

iny y;

should be

int y;

Then you might use a SortedSet (for example TreeSet),

Comparator<XNode> comp = new Comparator<XNode>() {
    @Override
    public int compare(XNode o1, XNode o2) {
        return Long.valueOf(o1.magicNumber).compareTo(o2.magicNumber);
    }
};
SortedSet<XNode> set = new TreeSet<>(comp);
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

Implement Comparable and compare by your magicNumber:

public int compare(XNode other) {
    return Long.compare(this.magicNumber, other.magicNumber);
}

and use a TreeSet.

steffen
  • 16,138
  • 4
  • 42
  • 81
2

There's no sorted list, but you can use a sorted set with a Comparator:

Set<XNode> set = new TreeSet<>((a, b) -> Long.compare(a.magicNumber, b.magicNumber));

This comparator (lambda) distinguishes sorts on magicNumber.

Bohemian
  • 412,405
  • 93
  • 575
  • 722