William Chandler
William Chandler

Reputation: 55

Sorting an array of objects by the objects field. How to make a Comparator? Java/Processing

I have a class called Creature and an array of Creature objects called creatures. The class Creature has an integer field called distance. I would like to sort the array creatures by their individual distance fields. I've tried several different ways but haven't gotten very far. Can someone explain to me how this works so I can figure out how to do it?

Creature [] creatures;
int [] distancearray;                      //I made a seperate array to try and order the 
                                           //creatures array based on this array

distancearray = new int [numcreatures];
for (int i = 0; i < numcreatures; i++) {
  distancearray[i] = creatures[i].distance;
}
distancearray = sort(distancearray);      //sorting this array was easy but idk how to 
                                          //sort creatures based on it
...

class Creature /*implements Comparable*/{//First attempt at Comparable
...
/*
  int compareTo(Object otherObject){                //First try with Comparable
    Creature otherCreature = (Creature)otherObject;
    if (distance < otherCreature.distance) {
      return -1;
    }
    if (distance > otherCreature.distance) {
      return 1;
    } else {
      return 0;
    }
  }

  int compare(Creature C2){                         //Second try with Comparable
    if (distance < C2.distance) {
      return -1;
    }
    if (distance > C2.distance) {
      return 1;
    } else {
      return 0;
    }
  }
*/
}

I sometimes get a static error, sometimes not. Am I setting the comparable up correctly? If so how do I then use it? I don't care how I get the array sorted but the easiest way would be nice. I am using Processing by the way.

These are some of the sources I've tried to use so far:

Making a generic comparator class

Java Sorting: sort an array of objects by property, object not allowed to use Comparable

How to sort an array of objects in Java?

Thanks!

Upvotes: 2

Views: 1230

Answers (1)

Eritrean
Eritrean

Reputation: 16498

The easiest way would be to use a Comparator. Assuming there is a getDistance method in your Creature class

import java.util.Arrays;
import java.util.Comparator;

//may be more of your Processing code

Creature [] creatures = //your array;

void setup() {
  //sort your array here or in whatever method you want
  Arrays.sort(creatures, Comparator.comparingInt(Creature::getDistance));
}

class Creature {
    // your class code
}

//may be more of your Processing code

Upvotes: 2

Related Questions