Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

treemap contains method classCastException

Status
Not open for further replies.

ketandba

Programmer
Nov 15, 2004
38
US
i have problem in TreeMap Contains method....
My treeMap name is Clienthistory(K,V)
where K = object (String clientName)
V = UserDefine LinkedList.
While appending the newClient.. if this new Client already Exist then i have to take the value(as a linkedList) and
append it in to the Exisiting LinkedList....Because before adding the client linkedlist in treemap it is already genereated..

every time i initialized the linked list for new client......

in my linkedList Add() method i used (Comparable obj) as an argument
************
public class LinkedList {
public void add (Comparable obj)
{
some statment for addition....
}

}

************
for creating treeMap ... i am using WriteRecord class....
I am usinf Sax parser for parse my xml document..

public class WriteRecord extends DefaultHandler{

private myDomain.LinkedList linkedRecordList = null;

----
--- some code ---

public void endElement(String uri, String localname, String qname)
throws SAXException {

---- some code ----

linkedRecordList.add(record); // --> for new client linkedlist is alreay generated
// i have to append in this linkedlist from exisiting treeMap...

if(qname.equals("client")){

bool = clientHistory.containsKey(clientName);
if (bool){
Object obj = clientHistory.get( clientName);

Comparable rec = (Comparable)obj; // because my LinkedList add method
// has Comparable obj argument

*************************************************************************************
here i got the classCast Exception.. i know that this casting is not allowed
But it is my requirement.........How i can do this...
*************************************************************************************

linkedRecordList.add(rec); // rec - Special Record type(contains date/discription/min)
// This linkedList contains (old + new) records for the client.....

clientHistory.remove(clientName); // for that client i remove the existing LinkedList
System.out.println("Record remove from tree map for the client = " + clientName);
}

clientHistory.put(clientName,linkedRecordList); // new linkedList contains (old+new) records
System.out.println("Record added for the client = " + clientName);

}

Your help is appriciated.....

ketan

 
Humm. I don't know if I fully understood your problem, but I guess you want to call a method that takes as argument a Comparable object with an object that doesn't extend Comparable?

Ok, as you said, you cannot do it.

Possible solutions:

1.- Add another add method to your LinkedList that accepts an Object as parameter.

2.- Make your special record type extend from Comparable.

Cheers.

Dian


 
hey,
dian,
i can't write new add method...because in my add method i am doing the sorting of my records at insertion time....

here my both class for your ready reference...

****
public class LinkedList {
Node front = null;
Node rear = null;
int num_items = 0; // Current number of items.

// Could this class use a constructor?

// Instance method to add a data item.
public void add (Comparable obj)
{
if (front == null) {
front = new Node (obj);
rear = front;
}
else {
// Find the right place.
Node temp_ptr=front, prev_ptr=front;
boolean found = false;
while ( (!found) && (temp_ptr != null) ) {
if (temp_ptr.data.compareTo(obj) > 0) {
found = true;
break;
}
prev_ptr = temp_ptr;
temp_ptr = temp_ptr.next;
}
// Now insert.
if (!found) { // Insert at rear.
rear.next = new Node (obj);
rear = rear.next;
}
else if (temp_ptr == front) { // Insert in front.
Node Lptr = new Node (obj);
Lptr.next = front;
front = Lptr;
}
else { // Insert in the middle.
Node Lptr = new Node (obj);
prev_ptr.next = Lptr;
Lptr.next = temp_ptr;
}
}
num_items++;
}

public ListIterator iterator(){
return new ListIterator(front);
}

public class Node {
Comparable data = null;
Node next = null;

// Constructor.
public Node (Comparable obj)
{
data = obj; next = null;
}

// Accessor.
public Comparable get_data ()
{
return data;
}

public String toString(){
return data.toString();
}
}
}
************here my Record class *****
public class Record implements Comparable{

Date date;
String description;
float hours;
static int returnValue;
Record next;
Record prev;
public Record(Date date, String description, float hours)
{
this.date=date;
this.description=description;
this.hours=hours;
}
public String toString(){
StringBuffer sb = new StringBuffer();
sb.append(date);
sb.append(description);
sb.append(hours);

return sb.toString();
}
public Date getDate() {
return date;
}

public void setDate(Date date) {
this.date = date;
}
public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}
public float getHours() {
return hours;
}

public void setHours(float hours) {
this.hours = hours;
}

public int compareTo(Object obj){

if (!(obj instanceof Record)){
System.err.println("This is not Record object...Record object is expected.");
}
// System.out.println("current date = " + getDate());
// System.out.println("new date = " + (((Record)obj).getDate()));
// System.out.println("return = " + getDate().compareTo(((Record)obj).getDate()));
return getDate().compareTo(((Record)obj).getDate());

}// end compareTo

}
 
Code:
import java.text.DateFormat;
import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;

class testcp
      {
       public static void main(String args[])
              {
               Calendar cal = Calendar.getInstance();
               long l = 86400000;
               float h = 60*60*1000;

//System.out.println(Calendar.ZONE_OFFSET);
               //Record r = new Record(cal.getTime(),DateFormat.parseString("))    
    Calendar thisDayZero = new GregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH 
));    
    // Get difference in milliseconds
    long diffMillis = cal.getTimeInMillis()-thisDayZero.getTimeInMillis();
//System.out.println("!!!"+diffMillis/(h));
               Record r = new Record(cal.getTime(),"describe1",diffMillis);
               LinkedList myLink = new LinkedList();
               myLink.add(new Node(r));
              }
      }
Code:
import java.util.*;
    public class Node implements Comparable{
         Comparable data = null;
          Node next = null;

          // Constructor.
          public Node (Comparable obj)
          {
            data = obj;  next = null;
          }
          
          // Accessor.
          public Comparable get_data ()
          {
            return data;
          }

        public String toString(){
            return data.toString();
        }
        public  int compareTo(Object obj){return 0;}
    }
Code:
import java.util.*;
public class LinkedList {
      Node front = null;
      Node rear = null;
      int num_items = 0;      // Current number of items.

      // Could this class use a constructor?

      // Instance method to add a data item.
      public void add (Comparable obj)
      {
        if (front == null) {
          front = new Node (obj);
          rear = front;
        }
        else {
          // Find the right place.
          Node temp_ptr=front, prev_ptr=front;
          boolean found = false;
          while ( (!found) && (temp_ptr != null) ) {
            if (temp_ptr.data.compareTo(obj) > 0) {
              found = true;
              break;
        }
            prev_ptr = temp_ptr;
            temp_ptr = temp_ptr.next;
          }
          // Now insert.
          if (!found) { // Insert at rear.
        rear.next = new Node (obj);
        rear = rear.next;
          }
          else if (temp_ptr == front) { // Insert in front.
        Node Lptr = new Node (obj);
            Lptr.next = front;
            front = Lptr;
          }
          else { // Insert in the middle.
        Node Lptr = new Node (obj);
        prev_ptr.next = Lptr;
        Lptr.next = temp_ptr;
          }
        }
        num_items++;
      }    
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top