Win a copy of Murach's Java Programming this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Comparable interface  RSS feed

 
Dana Ucaed
Ranch Hand
Posts: 323
6
Netbeans IDE Oracle Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Ranchers,

I found this question on "OCP Java SE 7 Programmer II
Certification Guide
by Mala Gupta
Bonus chapter 13"



The code throws an exception at runtime.

my question is: How to modify the code so I didn't receive runtime exception.

One solution incomplete is :

the class TestTreeSet implements Comparable<>

and  to override the method compareTo.

Thanks in advance.


 
Viktor Logwin
Ranch Hand
Posts: 99
15
Chrome Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, Dana,

the Problem is not the TreeSet itself, but the StringBuilder you're trying to use as generic type.
The StringBuilder class doesn't implement Comparable interface, so you can not add its objects to the TreeSet.

But you have a nice alternative to do it, using a Comparator. Please try to rewrite your initialization of the TreeSet object as follows:
 
Dana Ucaed
Ranch Hand
Posts: 323
6
Netbeans IDE Oracle Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you Viktor.

I know that the issue is that StringBuilder is not implemented Comparable but I think that if my class implements Comparable then and TreeSet<StringBuilder> implements Comparable.

How's your score questions about collections for OCP exam?

 
Viktor Logwin
Ranch Hand
Posts: 99
15
Chrome Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How's your score questions about collections for OCP exam?

Not good enough. I have read the chapter and made a summary, then I've made the chapter test, had more, than 65%, but there are many things to remember, so I will return to my summaries later and will practice writing code after I have read all the chapters.
This is my standard walk-through

About Comparable and Comparator you need to know, that you can use a Comparator
- when you need a custom sorting order or
- when the objects you want to sort (or add to a sorting collection) don't implement Comparable.
You can not change those objects to make them implement Comparable, but you can say a collection or a sorting method to use your custom Comparator.
 
Dana Ucaed
Ranch Hand
Posts: 323
6
Netbeans IDE Oracle Windows
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is my correct version:



If I have String instead of StringBuilder I didn't need another class.

 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!