Meaningless Drivel is fun!*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question about Collections.sort() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question about Collections.sort()" Watch "Question about Collections.sort()" New topic
Author

Question about Collections.sort()

MuraliH Krishna
Greenhorn

Joined: Jan 19, 2008
Posts: 9
HI,
can any one kindly explain what is the mistake I am doing in the following code. Why it is not compiling.

import java.util.*;
public class CollectionTest1 {
public static void main(String[] a)
{
Set<animal> s = new HashSet<animal>();
s.add(new animal("aa"));
s.add(new animal("ab"));
s.add(new animal("ac"));
s.add(new animal("ad"));

animal[] ar = (animal[])s.toArray();
Collections.sort(s);

}

}

class animal implements Comparable<animal>
{
String i;
animal(String i)
{
this.i = i;
}
public String getI()
{
return i;
}
public int compareTo(animal a1) {
return i.compareTo(a1.getI());
}
}

Thanks in advance.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18509
    
  40

Why it is not compiling.


It would help if you tell us the compiler error that you are getting.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Erica Barbato
Greenhorn

Joined: Oct 01, 2007
Posts: 8
Hi, Collections.sort needs a List as parameter,but you are using a Set
[ January 20, 2008: Message edited by: erishine ]

SCJP 5.0, SCWCD 5
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Question about Collections.sort()
 
Similar Threads
HashSet
HashSet and sorting
Generic
Do HashSets allow duplicates?
Collection VS ArrayList.