permaculture playing cards*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes TreeSet Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "TreeSet Question" Watch "TreeSet Question" New topic
Author

TreeSet Question

Richard Wilson
Ranch Hand

Joined: Jan 12, 2002
Posts: 57
Can I add different types of objects into a treeset if no comparator provided?
For example,add Integer and String will cause
any exception?


Richard Wilson
Jose Botella
Ranch Hand

Joined: Jul 03, 2001
Posts: 2120
If the objects haven't got a Comparator, they will have to implement the Comparable interface. The method compareTo in this interface, according to API, must throws a ClassCastException if the type of the argument prevents the comparation.


SCJP2. Please Indent your code using UBB Code
Stephen Batsas
Ranch Hand

Joined: Jan 22, 2002
Posts: 117
Richard,
This is a snippet of code I cut yesterday to implement the Comparator interface. You can add any type of object to a TreeSet as long it implements the Comparator interface. In this program I have used it to sort a vector. The interface method compareTo throws a ClassCast exception so it should be handled in serious code.
Here it is:
// TestCust.java
// 2/4/2002
// Implementing the Comparator interface
import java.util.*;

class Customer implements Comparator{

private String name,phone;
Customer(String n,String p){
name = n;
phone = p;
}
String get(){
return ("Name: " + name + " , " + "Phone: " + phone);
}
public int compare(Object ob1, Object ob2){
Customer c1 = (Customer)ob1;
Customer c2 = (Customer)ob2;
String s1 = c1.name;
String s2 = c2.name;
int result = s1.compareTo(s2);
return result;
}
public boolean equals(Object rhs){
String s1 = this.name;
Customer c = (Customer)rhs;
String s2 = c.name;
int result = s1.compareTo(s2);
if(result == 0)
return true;
else
return false;
}
}
public class TestCust{
static Vector Customers = new Vector();

public static void main(String args[]){
Customer C = new Customer("","");
Customers.add(new Customer("steve","4395939"));
Customers.addElement(new Customer("Betty","84384383"));
Customers.add(new Customer("Anne","3294393"));
Collections.sort(Customers,C);
Iterator i = Customers.iterator();
for(;i.hasNext(); ){
Customer c = (Customer)i.next();
String s = c.get();
System.out.println(s);
}
System.out.println(Customers);
}
}
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: TreeSet Question