How do I sort an array of objects by their attribute?

edited February 2017 in How To...

Let's say I define a class with int x and int y, and make an array of instances of that class. How can I sort that array by x values in decreasing order?

Answers

  • edited February 2017

    http://docs.Oracle.com/javase/8/docs/api/java/util/Arrays.html#sort-java.lang.Object:A-

    http://docs.Oracle.com/javase/8/docs/api/java/lang/Comparable.html

    https://forum.Processing.org/two/discussions/tagged?Tag=compareto()

    /**
     * Comparable Dots (v1.0)
     * GoToLoop (2017-Feb-19)
     *
     * https://forum.Processing.org/two/discussion/20852/
     * how-do-i-sort-an-array-of-objects-by-their-attribute#Item_1
     */
    
    static final short DOTS = 5;
    final Dot[] dots = new Dot[DOTS];
    
    void setup() {
      size(300, 200);
      noLoop();
      for (int i = 0; i < DOTS; dots[i++] = new Dot());
      mousePressed();
    }
    
    void draw() {
      background((color) random(#000000));
      frame.setTitle("Frame: " + frameCount);
    }
    
    void keyPressed() {
      mousePressed();
    }
    
    void mousePressed() {
      for (final Dot d : dots) {
        final int x = (int) random(width);
        final int y = (int) random(height);
        d.setXY(x, y);
      }
    
      println();
      println(dots);
    
      java.util.Arrays.sort(dots);
      println(dots);
    
      redraw = true;
    }
    
    class Dot implements Comparable<Dot>, Cloneable {
      short x, y;
    
      Dot() {
      }
    
      Dot(final int x, final int y) {
        setXY(x, y);
      }
    
      Dot setXY(final int px, final int py) {
        x = (short) px;
        y = (short) py;
        return this;
      }
    
      @Override int compareTo(final Dot d) {
        //return x - d.x; // Ascending
        return d.x - x; // Descending
      }
    
      @Override int hashCode() {
        return x | y << 020;
      }
    
      @Override boolean equals(final Object o) {
        return o.hashCode() == hashCode();
      }
    
      @Override String toString() {
        return "[" + x + ", " + y + "]";
      }
    
      @Override Dot clone() {
        try {
          return (Dot) super.clone();
        }
        catch (final CloneNotSupportedException cause) {
          throw new RuntimeException(cause);
        }
      }
    }
    
Sign In or Register to comment.