File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

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
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:
// 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 =;
String s2 =;
int result = s1.compareTo(s2);
return result;
public boolean equals(Object rhs){
String s1 =;
Customer c = (Customer)rhs;
String s2 =;
int result = s1.compareTo(s2);
if(result == 0)
return true;
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"));
Iterator i = Customers.iterator();
for(;i.hasNext(); ){
Customer c = (Customer);
String s = c.get();
I agree. Here's the link:
subject: TreeSet Question
It's not a secret anymore!