We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi folks,
I am trying to sort a Comparable class called Tree by its height h. I tried using the Arrays.sort () function, but it does not compile and the error message is: 'Cannot find anything named "Arrays"'. I tried using collections.sort (), but get the equivalent error message. The code is as follows:
class Tree implements Comparable {
int h;
Tree (int tempH) {
h = tempH;
}
// Make Trees comparable by height
int compareTo(Object o){
Tree e = (Tree) o;
return h-e.h;
}
void draw (){
nums = 2000;
Tree [] trees = new Tree [nums];
// Loop over the number of individuals
//Some code that puts heights into the 2000 trees.
trees = Arrays.sort(trees);
}
I use data from a file that is read in for a particular year and gives all trees its height. The bit of code that allocates height to trees definitively works, but is quite long so I omitted it.
I have never used Comparable classes before and I am still not sure I have understood them, so any pointer would be very much appreciated.
Cheers, finisTTR
Answers
add to the top of file
(newer processing versions don't import as much as the older versions so you have to so it yourself)
That fixed it! Thanks, koogs!
Addendum:
return h - (Tree) o.h;
only works if field h is NEVER negative. Breaks Comparable's contract!It's not your case here, since h is Tree's height. But for other folks doing the same, but negative is possible:
return Integer.signum(h - (Tree) o.h);
P.S.: If you just use sort() in 1 or 2 places only, you can go w/ explicit:
java.util.Arrays.sort(trees);
rather than
import java.util.Arrays
+Arrays.sort(trees);
:-jExtra: We can specify the type to be used in Comparable:
class Tree implements Comparable<Tree> {}
This way we don't need to use Object as parameter type, but go straight to Tree: :D
Ah! A Tree example from an old thread: =:)
http://forum.processing.org/two/discussion/1645/trees
"SortedForest.pde":
"Tree.pde":