We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi, So I am trying to this basic insertion sort of an ArrayList.. Is there a way I can use java's 'compareTo' function in processing? I tried importing all sorts of java libs.. Still having the error 'the function compareTo in not defined'.. Thanks,
void _sort(ArrayList<Word> A) {
for (int i=0; i < A.size(); i++) {
Word a = A.get(i);
int pos = i;
while ( (pos > 0) && (a.compareTo(A.get(pos-1)) >=1 )) {
A.set(pos, A.get(pos-1));
pos--;
}
A.set(pos, a);
}
}
Answers
In order to use
compareTo()
, your object to be compared (in this caseWord
) must implementComparable
. This is part of native Java, but that doesn't mean you can't use it - it just isn't documented in Processing.Note: Processing (and Java) already have a built-in
sort()
function. In many cases, this function will be more efficient than anything you try to concoct yourself. You'll still need to useComparable
, though...More
Comparable
links:http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/ http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html http://stackoverflow.com/questions/3718383/java-class-implements-comparable
P.S.: Java (and, inherently, Processing) language customs suggest that you use lowercase initial characters in variable names - so
A
would becomea
. There's nothing wrong with your code, but it can improve readability to other people reviewing your code. Similarly, we don't normally start our function names with an underscore, but I'm not sure if this custom is as widely used as the previous one (and it is understandable, seeing as there is already a built-insort()
function as described above).Great! Thanks.. I understand using 'sort' would be much better but I am following this example(though he uses eclipse).. Right, so I tried using 'class Word implements Comparable ' and defined a function in word class-
Now the error I am getting is' the type--.Word must implement the inherited abstracted method Comparable<..>
Oh! Nevermind! It worked! Thanks a lot for the links..
In this post below, I've got an example where a classed named Card implements Comparable<Card>.
Maybe it's worth to take a look if you're still having problems: :-/
forum.processing.org/two/discussion/2801/picking-cards-at-random-then-excluding-those-from-further-picking-
Awesome! Thanks..
How did you fix the "Word must implement the inherited abstracted method Comparable<..>" error. I'm getting it too, even though I've implemented the compareTo method
int compareT0(Car compareCar) { float compareFitness = ((Car)compareCar).fitness; if (fitness > compareFitness) { return 1; } else { return 0; } }
Thanks
nvm I got it
Well, @calsign has answered the question. Meanwhile I would suggest to refer below resource for more examples on compareTo() method, http://www.flowerbrackets.com/two-best-ways-in-java-to-sort-string-array/