Using Comparable interface in Sorting Cards Exercise, week 8 #15, or #122 for whole course

332 views
Skip to first unread message

Alan Aho

unread,
Oct 15, 2014, 4:53:22 PM10/15/14
to moo...@googlegroups.com
Hi,

I'm having problems with week 8 exercise 15.

*Explain your problem here*

I used the Comparable interface in the Card class and coded compareTo so that the cards would sort properly.  I tested it in the main rtn with no problem.  When  I did the "Hand" part of the exercise, I did not use the "comparable" interface, and just used the Collections.sort as my sort routine in the Hand.sort method.  It worked.  I changed the compareTo override code in Card to reverse the sequence in my test and it showed in the result.  When I submitted the test, I got a msg saying I needed to make class Hand implement the Comparable interface.  When I try to do that, I have no idea how to code the override to compareTo to satisfy the interface requirement.  H
ow do I reference the "current" object in the compareTo  coding if I am not in the Card class?

I figured that overriding compareTo in the class whose objects are to be sorted was the important thing, and would satisfy sorting requirements in any coding that used Card objects, and that seems to be correct.  So why do I need to use Comparable in the Hand class?

Your help is greatly appreciated.

Best regards
___________


Jarmo Isotalo

unread,
Oct 15, 2014, 5:01:33 PM10/15/14
to Alan Aho, moo...@googlegroups.com
What exactly you are supposed to do in that exercise?
part of it is to implement compareTo(Hand other) method to class Hand, so that different hands can be compared and hands could be sorted. 
And as we want to be able to sort those, the java way of accomplishing it is to implement interface Comparable<T> and then compareTo(T other)

(T == Type. In the case of card Card and now in the case of hand Hand)

Just like in Card, you can use this as the reference to the current object also in when implementing compareTo to Hand.




--
http://mooc.fi
---
You received this message because you are subscribed to the Google Groups "mooc.fi" group.
To unsubscribe from this group and stop receiving emails from it, send an email to moocfi+un...@googlegroups.com.
To post to this group, send email to moo...@googlegroups.com.
Visit this group at http://groups.google.com/group/moocfi.
To view this discussion on the web visit https://groups.google.com/d/msgid/moocfi/6d3bbdef-48a7-4f27-af39-e54198e45916%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Alan Aho

unread,
Oct 15, 2014, 8:24:59 PM10/15/14
to moo...@googlegroups.com, ludd...@gmail.com

I think the error msg was for the next section where you compare hands.  I was doing the hand sorting part (the previous section) and I misunderstood the error as applying to hand sorting, not hand comparison.  So no problem after all.  Sorry to bother you.
Reply all
Reply to author
Forward
0 new messages