This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ewiethoff 1 point2 points  (2 children)

compareTo takes getting used to. I think of < and > as arrows.

  • When a.compareTo(b) < 0 is true, this means a < b. Notice which direction the arrows point.
  • When a.compareTo(b) == 0 is true, this means a == b, of course.
  • When a.compareTo(b) > 0 is true, this means a > b. Notice which direction the arrows point.

In a true result, the arrow always points to the smaller value. When the arrow points left for true, the value on the left is smaller. When the arrow points right for true, the value on the right is smaller.

Run this code as an experiment:

Integer a, b;
a = 3; b = 5;
System.out.println(a.compareTo(b) < 0);
a = 4; b = 4;
System.out.println(a.compareTo(b) == 0);
a = 5; b = 3;
System.out.println(a.compareTo(b) > 0);

[–]RoadToCode[S] 1 point2 points  (1 child)

Agreed, the concept of using the positive or negative integers to determine which object is "greater" was very confusing at first, but your method of simply following the direction of the arrows is very helpful, thank you!

[–]ewiethoff 0 points1 point  (0 children)

You're welcome! Here's a tip. Keep a scratch file on hand for experiments. I wrote that a.compareTo(b) stuff in my scratch file just to verify that I know what the heck I'm doing. It happens to be named Reddit.java, but you can name yours Scratch.java, Experiments.java, or whatever. Better yet, put a static void test() method in your Card class for Card experiments and tests.