Re: Comparable Interface
On 06/16/2010 12:39 AM, Arthi J wrote:
public class Drink implements Comparable {
Comparable<what?>
public String address;
public String name;
public int compareTo(Object o) {
return 1;
Where's the "compare" in "compareTo()"? I don't see any comparison.
By the way, where's your indentation?
}
}
import java.util.*;
public class testClass
Class names should begin with an upper-case letter.
{
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();
TreeSet<what?>
set.add(one);
set.add(two);
Iterator it = set.iterator();
Iterator<what?>
while(it.hasNext())
{
Drink temp = (Drink) it.next();
System.out.println(temp.name);
System.out.println(temp.address);
}
}
}
Output:
-----------
Coffee
b
Tea
a
----------
Why is it that sorting occurs only based on 'Name' string here and not
on 'Address' string when inserted into TreeSet?
"compareTo()" is supposed to compare to something. ("what?")
You forgot your generics.
Your indentation is inconsistent and irregular and not standard.
--
Lew