Comparable Interface

A

Arthi J

public class Drink implements Comparable {
public String address;
public String name;

public int compareTo(Object o) {
return 1;
}
}

import java.util.*;
public class testClass
{
public static void main(String args[])
{
Drink one = new Drink();
Drink two = new Drink();
one.address = "b";
two.address = "a";
one.name= "Coffee";
two.name= "Tea";

TreeSet set = new TreeSet();
set.add(one);
set.add(two);
Iterator it = set.iterator();
while(it.hasNext())
{
Drink temp = (Drink) it.next();
System.out.println(temp.name);
System.out.println(temp.address);
}
}
}

Output:
 
M

markspace

Arthi said:
> Why is it that sorting occurs only based on 'Name' string here and not
> on 'Address' string when inserted into TreeSet?


I don't think that's what's occuring at all.

public class Drink implements Comparable {
public String address;
public String name;

public int compareTo(Object o) {
return 1;
}
}


Is this a homework question? Look at this method again and tell me what
the sorting is based on.
 
T

Tom Anderson

public class Drink implements Comparable {
public String address;
public String name;

public int compareTo(Object o) {
return 1;
}
}

import java.util.*;
public class testClass
{
public static void main(String args[])
{
Drink one = new Drink();
Drink two = new Drink();
one.address = "b";
two.address = "a";
one.name= "Coffee";
two.name= "Tea";

TreeSet set = new TreeSet();
set.add(one);
set.add(two);
Iterator it = set.iterator();
while(it.hasNext())
{
Drink temp = (Drink) it.next();
System.out.println(temp.name);
System.out.println(temp.address);
}
}
}

Output:
-----------
Coffee
b
Tea
a

You're kidding, right?

tom
 
D

Daniel Pitts

Why is it that sorting occurs only based on 'Name' string here and not
on 'Address' string when inserted into TreeSet?

Because your teacher is failing at his/her job and your book is out of
date. I suggest replacing both as soon as possible. If you can not
replace your instructor, at least supplement the book with a recent one
explaining Java.
 
E

Eric Sosman

Then it should use
return 0;
as that is at least a consistent implementation (only one equivalence class).

Still better, IMHO, is

public int compareTo(Object o) {
throw new UnsupportedOperationException("FIX ME!");
}

(This is approximately what NetBeans generates for you when you tell
it to implement the missing methods required by an interface or by
an abstract superclass.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,701
Latest member
XavierQ83

Latest Threads

Top