Comparable does not compare

A discussion forum for JFreeChart (a 2D chart library for the Java platform).
Locked
montechristos
Posts: 1
Joined: Thu Dec 28, 2006 6:17 pm

Comparable does not compare

Post by montechristos » Thu Dec 28, 2006 6:27 pm

Hello all,

I am relatively new to JFreeChart...

I am using a DefaultCategoryDataset to populate my graph.
So I created a Comparable for Dates that is:

Code: Select all

	private class ComparableFormattedDate implements Comparable<ComparableFormattedDate> {
		private Date date;
		
		public ComparableFormattedDate(Date date) {
			this.date = date;
		}
		
		@Override
		public String toString() {
			return getFormattedDate(date);
		}

		public int compareTo(ComparableFormattedDate o) {
			int res = date.compareTo(o.date);
			
			System.err.println(String.format("Comparing date %s to %s and got: %d", getFormattedDate(date), getFormattedDate(o.date), res));
			
			return res;
		}
	}
However my compareTo function is never called.
Internally it must be using the == instead of my compareTo method cause if I put the same comparable Objects, it seems to work.

I believe this is a bug, can somebody comment on this?

Thanks in advance

ahill
Posts: 7
Joined: Mon Nov 20, 2006 11:22 pm
Location: Singapore

Post by ahill » Mon Jan 08, 2007 3:22 am

You should probably override equals and hashCode too.

The default implementation in Object is just:

Code: Select all

public boolean equals(Object obj) {
	return (this == obj);
Theres lengthy waffle about the need for consistency between equals, hasCode, and compareTo in the relevant javadocs, so its probably something to do with that.

(I too have burned countless hours tracking down odd collections related issues when I made a mess of implementing Comparable and its associated methods!...)

smallet
Posts: 2
Joined: Wed Feb 21, 2007 4:33 pm
Location: Paris
Contact:

Re: Comparable does not compare

Post by smallet » Wed Feb 21, 2007 4:35 pm

montechristos wrote:However my compareTo function is never called
I'm having the same problem. Any news ?

david.gilbert
JFreeChart Project Leader
Posts: 11734
Joined: Fri Mar 14, 2003 10:29 am
antibot: No, of course not.
Contact:

Post by david.gilbert » Wed Feb 21, 2007 6:01 pm

You need to override equals().
David Gilbert
JFreeChart Project Leader

:idea: Read my blog
:idea: Support JFree via the Github sponsorship program

smallet
Posts: 2
Joined: Wed Feb 21, 2007 4:33 pm
Location: Paris
Contact:

Post by smallet » Wed Feb 21, 2007 6:28 pm

thanx for your fast reply.
the problem is that i already overide equals() and hashCode()

could the problem comes from the fact i'm using a DefaultCategoryDataset wich create its data using DefaultKeyedValues2D default constructor wich use false as value for sortRowKeys field ?

Locked