Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Data Structures - Retired Organizing Data Interfaces

Video question @ 3:15.

Craig stated that comparing x .....to...... y == -sgm(y.....to..... x) are inversely related and that the first yields -1 so the second should yield 1. I'm not trying to be anal here but should I take it as the value of both should be the opposite of each other as oppose to inversely related b/c stating that a value is inversely goes as follows: the inverse of 2 = 1/2, -3 = -1/3, etc.

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Hi Sandy,

I have tried to understand this ... but all I got was headache and bad mood :)

2 Answers

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Sandy;

Take a look at the Comparable docs that Craig was viewing. What that is basically saying is that if we do x.compareTo(y) we get returned to us one of three values, -1, 0, or 1, depending on the comparison, right?

For example...

class Main {
  public static void main(String[] args) {
    Integer x = 3;
    Integer y = 5;

    System.out.println(x.compareTo(y));
  }
}

Since x is less than y, we get a -1 as a result. The inverse portion that is discussed in the video and in the documentation is that we need to assume and expect that if our output of x.compareTo(y) results in -1 that if we do y.compareTo(x) we will get a 1. That make sense, right? In the example code x is less than y so we get a -1. Using the same numbers then, y is greater than x must return a 1.

It is part of the contract we enter into when we implement Comparable we guarantee that we are going to provided the required information in a proper format, and Java guarantees it isn't going to act odd and say "Yea, 3 is less than 5, but 5 is also less than 3" when we do the compareTo() method check.

Does that help clear anything up? Post back if you still have questions or my ramblings don't make sense.

Happy coding,
Ken

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Ken,

perfect explanation !!!!!

Thank you ...

Ken, thanks for your help. Your explanation helped solidify my understanding of the comparable interface doc. The only hang up I had was the term inverse mainly for future references when dealing with numbers that aren't whole.