wood burning stoves*
The moose likes Beginning Java and the fly likes Comparator() error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Comparator() error" Watch "Comparator() error" New topic
Author

Comparator() error

nirjari patel
Ranch Hand

Joined: Apr 23, 2009
Posts: 364


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

Joined: Oct 25, 2008
Posts: 2700

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.


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Vinoth Kumar Kannan
Ranch Hand

Joined: Aug 19, 2009
Posts: 276

Yeah, Set doesn't have one, but TreeSet has.

might work.


OCPJP 6
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37970
    
  22
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

Joined: Oct 27, 2005
Posts: 19651
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37970
    
  22
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?"
 
Don't get me started about those stupid light bulbs.
 
subject: Comparator() error
 
Similar Threads
adding objects with same hashcodes and true value return by equals() method to a set.
How does "natural ordering" works for strings
HashSet
Generics Compiler error
java pass by value.