Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

TreeSet Question

 
Richard Wilson
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can I add different types of objects into a treeset if no comparator provided?
For example,add Integer and String will cause
any exception?
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Stephen Batsas
Ranch Hand
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic