Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparator() error

 
nirjari patel
Ranch Hand
Posts: 386
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


This class is named as SetTest.java
When I compile this code, I am getting following error.

"SetTest.java:14: cannot find symbol
symbol : method comparator()
location: interface java.util.Set
Comparator c = set.comparator();
^
Note: SetTest.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error"

Why am I gettingn this error, comparator() is in the java.util.Set.

How can I use comparator() to compare objects ? Do I need to override this method ? If yes, then wheta difference between equals() and comparator() ?

Thanks

 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no method called comparator in java.util.Set. Some set's use a comparator do order there elements, such as a TreeSet. But then the elements need to implement the Comparable interface or a Comparator must be provided a creation time.
 
Vinoth Kumar Kannan
Ranch Hand
Posts: 276
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah, Set doesn't have one, but TreeSet has.

might work.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49756
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Probably a good idea to go through the TreeSet documentation first, and see where that Comparator<T> comes from. Also, see what the comparator() method returns.
 
Rob Spoor
Sheriff
Pie
Posts: 20606
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vinoth Kumar Kannan wrote:Yeah, Set doesn't have one, but TreeSet has.

might work.

That should be Code against interfaces as much as possible. Since SortedSet declares the comparator() method it's better to use that interface. That allows you to more easily switch to a different implementation (like ConcurrentSkipListSet) if needed.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49756
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This reminds me of the "what happens next?" bit on a home video TV programme. They show half the video, and about one second before something strange happens, the commercials come on, so you have to wait several minutes to find out what happens.

Anyway, let's have a programming "what happens next?"
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic