Solved

ClassCastException while implementing  Comparable interface and its compareTo method

Posted on 2004-09-16
19
773 Views
Last Modified: 2013-12-29
Hi All,
   Hope you all are doing good....
   Here I am having a bit bitter experience in using a Comparable interface and its compareTo method.

The thing is iam trying to sort a collection of objects . The object contains 5 fields- one int 2 Date and 3 string fileds and these fileds have respective getter and setter method in a bean where I have implemented Comparable interface and its method compareTo.

And all this is done in structs-Tomcat.

I get ClassCastException though I get an output in the screen. Its sorting in the ascending order, allright.. but I need to remove the classcastexception and after that I need to sort them in the descending order...

Thanks in advance
Hara
0
Comment
Question by:haravallabhan
  • 8
  • 5
  • 3
  • +2
19 Comments
 
LVL 37

Expert Comment

by:zzynx
ID: 12073678
Difficult to say without any code, you know...
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12073743
Firstly check that all the objects in the collection are of the same type. Then have a look at the compareTo of the bean on its own
0
 
LVL 1

Author Comment

by:haravallabhan
ID: 12073805
How do I check if all the objects in the collection are of the same type....
Ok Here is the code....

this is the bean implementing comparable
Bean------------->
public class MyInitiativeBean implements Comparable,Serializable{
      public static String currentField="id";
      private int initiativeId; //field name= id
      private String title;//field name= title
      private String objective;//field name= objective
      private String keyContact;//field name= keyContact
      private String startDate;//field name= startDate
      private String endDate;//field name= endDate
      private String rejReasonX;//field name= rejReasonX
                                                                              //  Initiative ID
      public void setInitiativeId(int ini.......
....................................
.....................................
....................................
.....................................
....................................
.....................................
public int compareTo(Object anotherObject) throws ClassCastException{
                  if(anotherObject instanceof MyInitiativeBean){
                        System.out.println(":::YES IT IS  A INSTANCE of MyInitiativeBean:::");
                  
                  MyInitiativeBean anotherBean=(MyInitiativeBean)anotherObject;
            
                  if(currentField.trim().equalsIgnoreCase("id")){
                     int id2=anotherBean.getInitiativeId();
                     System.out.println(initiativeId+":::ID2:::"+id2);
                     if(initiativeId >id2){
                           return 1;      
                     }
                     System.out.println(":::initiativeId:::"+initiativeId);
                     if(initiativeId < id2){
                        return -1;      
                     }
              }else if(currentField.trim().equalsIgnoreCase("title")){
                      String title2=anotherBean.getTitle();
                      if(title instanceof Comparable && title2 instanceof Comparable ){
                                  return title.compareTo(title2);      
                      }..................
.....................................................................

Action Class---------------approvedInitiativeList is the one to be sorted---------->

public class SetInitiativeAction extends Action {
      public ActionForward execute(ActionMapping mapping,
                  ActionForm form,
                  HttpServletRequest request,HttpServletResponse response)
      throws Exception{
            .................................................
,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.............................


Collection approvedInitiativeList=new ArrayList();
            
            approvedInitiativeList=(ArrayList)session.getAttribute("approvedInitiativeList");
            if(approvedInitiativeList==null)
                  approvedInitiativeList=(Collection)myInitiativeService.getApprovedInitiatives();
            if(previousField.trim().equalsIgnoreCase(MyInitiativeBean.currentField.trim())){
                  if(sorted.equals("asc")){
                        Collections.sort((ArrayList)approvedInitiativeList);
.................................
...........................

Thanks
Hara
0
 
LVL 16

Expert Comment

by:krakatoa
ID: 12073839
>> Object anotherObject ...

try it with the actual subclass object type, instead of Object.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12073842
>> How do I check if all the objects in the collection are of the same type.

Iterator it = approvedInitiativeList.iterator();
while (it.hasNext()) {
    if ( !it.next() instanceof YourObjectType )     // <<<<<<<<< MyInitiativeBean of whatever
       System.out.println("Element of wrong type found!");
}

That compareTo() looks OK

Can you tell us at what line you get the ClassCastException?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12073863
>> How do I check if all the objects in the collection are of the same type.

Well you shouldn't need to write additional code to do that, as you'll get an exception (the one you're getting ;-)) I meant really to check that this is unlikely from how you're filling it. The important thing is to figure out *where* the exception is occuring
0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 12073930
with the following code:

                   String title2=anotherBean.getTitle();
                   if(title instanceof Comparable && title2 instanceof Comparable ){
                             return title.compareTo(title2);     
                   }..................


since "title" is a string, and "anotherBean.getTitle()" returns a string, why not just call "title.compareTo(title2)" without the extra code, as java.lang.String implements Comparable by definition, i.e. the 2 tests for instanceof Comparable is redundant..

Also, you've not posted the entire compareTo() method....

Can you post the exception stack trace please?
0
 
LVL 1

Author Comment

by:haravallabhan
ID: 12073985
>>Can you tell us at what line you get the ClassCastException?

I dont have any idea.... as the code is executing and the sorting is working perfectly so far.....

and I checked to see that every object in the collection is an instance of the bean in which Iimplement the comparable interface

I shall also copy the whole of action code , hoping that it will help you all more to help me...:)

And the collectiona has only 3 objects of instance MyInitaitiveBean..
Action class----->

public class SetInitiativeAction extends Action {
      public ActionForward execute(ActionMapping mapping,
                  ActionForm form,
                  HttpServletRequest request,HttpServletResponse response)
      throws Exception{
            
            HttpSession session=request.getSession(true);
            String sorted=request.getParameter("sorted");
            if(sorted==null)sorted="asc";
            //MyInitiativeBean myInitiativeBean=new MyInitiativeBean();
            String previousField=MyInitiativeBean.currentField;
            String field=request.getParameter("field");
            if(field==null)
                  field="id";            
            System.out.println("Prev Field name ::"+previousField);
            MyInitiativeBean.currentField=field;
            MyInitiativeService myInitiativeService=new MyInitiativeService();
            Collection approvedInitiativeList=new ArrayList();
            
            approvedInitiativeList=(ArrayList)session.getAttribute("approvedInitiativeList");
            if(approvedInitiativeList==null)
                  approvedInitiativeList=(Collection)myInitiativeService.getApprovedInitiatives();
                  Iterator itr=approvedInitiativeList.iterator();
                  while(itr.hasNext()){
                        if(!(itr.next() instanceof MyInitiativeBean))
                              System.out.println("Not an object ---M...I...B");
                        else
                              System.out.println("IS an object ---M...I...B");
                  }
            if(previousField.trim().equalsIgnoreCase(MyInitiativeBean.currentField.trim())){
                  if(sorted.equals("asc")){
                        Collections.sort((ArrayList)approvedInitiativeList);
                        request.setAttribute("sorted","desc");
                  }else{
                        Collections.reverse((ArrayList)approvedInitiativeList);.......................
.....................................

Runtime error....:

SEVERE: Error creating form bean of class com.myinitiatives.MyInitiativeBean
java.lang.ClassCastException
      at org.apache.struts.util.RequestUtils.createActionForm(RequestUtils.java:837)
      at org.apache.struts.action.RequestProcessor.processActionForm(RequestProcessor.java:364)
      at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:253)
      at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
      at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:507)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:743)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:284)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:204)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:257)
      at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:151)
      at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:564)
      at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:245)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:199)
      at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:151)
      at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:564)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:195)
      at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:151)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:164)
      at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:149)
      at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:564)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:156)
      at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:151)
      at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:564)
      at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:972)
      at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:206)
      at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:828)
      at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:700)
      at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:584)
      at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:683)
      at java.lang.Thread.run(Thread.java:534)
Prev Field name ::id
IS an object ---M...I...B
IS an object ---M...I...B
IS an object ---M...I...B
:::YES IT IS  A INSTANCE of MyInitiativeBean:::
1000002:::ID2:::1000001
:::YES IT IS  A INSTANCE of MyInitiativeBean:::
1000002:::ID2:::1000003
:::initiativeId:::1000002
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12074064
Can you post the ***entire*** compareTo() method, please?
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 1

Author Comment

by:haravallabhan
ID: 12074306
ok here it is...

But I tried commenting all the code inside compareTo... it still gives me ClassCastException...
Here is my compare to..

public int compareTo(Object anotherObject) throws ClassCastException{
                  if(anotherObject instanceof MyInitiativeBean){
                        System.out.println(":::YES IT IS  A INSTANCE of MyInitiativeBean:::");
                  
                  MyInitiativeBean anotherBean=(MyInitiativeBean)anotherObject;
            
                  if(currentField.trim().equalsIgnoreCase("id")){
                     int id2=anotherBean.getInitiativeId();
                     System.out.println(initiativeId+":::ID2:::"+id2);
                     if(initiativeId >id2){
                           return 1;      
                     }
                     System.out.println(":::initiativeId:::"+initiativeId);
                     if(initiativeId < id2){
                        return -1;      
                     }
              }else if(currentField.trim().equalsIgnoreCase("title")){
                      String title2=anotherBean.getTitle();
                      //if(title instanceof Comparable && title2 instanceof Comparable ){
                                  return title.compareTo(title2);      
                      //}
              }else if(currentField.trim().equalsIgnoreCase("objective")){
                      String objective2=anotherBean.getObjective();
                      //if(objective instanceof Comparable && objective2 instanceof Comparable ){
                      return title.compareTo(objective2);      
                      //}
              }else if(currentField.trim().equalsIgnoreCase("keyContact")){
                      String keyContact2=anotherBean.getKeyContact();
                      //if(keyContact instanceof Comparable && keyContact2 instanceof Comparable ){
                      return keyContact.compareTo(keyContact2);      
                      //}
              }else if(currentField.trim().equalsIgnoreCase("startDate")){
                      String startDate2=anotherBean.getStartDate();
                      //if(startDate instanceof Comparable && startDate2 instanceof Comparable ){
                      return startDate.compareTo(startDate2);      
                      //}
              }else if(currentField.trim().equalsIgnoreCase("endDate")){
                      String endDate2=anotherBean.getEndDate();
                      //if(endDate instanceof Comparable && endDate2 instanceof Comparable ){
                      return endDate.compareTo(endDate2);      
                      //}
              }else if(currentField.trim().equalsIgnoreCase("rejReasonX")){
                      String rejReasonX2=anotherBean.getRejReasonX();
                      //if(rejReasonX instanceof Comparable && rejReasonX2 instanceof Comparable ){
                      return rejReasonX.compareTo(rejReasonX2);      
                      //}
              }  
            }
        return 0;
      }
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12074365
>> I tried commenting all the code inside compareTo... it still gives me ClassCastException...
Then it's rather clear that the reason of the error has to be found somewhere else ;°)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12074426
I think you get the error because MyInitiativeBean isn't an ActionForm (it should be)
0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 12074444
if the sort is working correctly, then the exception is probably not caused by the compareTo() method (which the exception stack trace indicates too)...

In your code above (not the compareTo() code, but the one posted at 05.29) there is quite a lot of intermixing Collection and ArrayList casts, and in particular casting Collections returned from other method calls to ArrayLists, which is not a good idea, as the object returned might be a Collection that is not an ArrayList...

From the stack trace, org.apache.struts.util.RequestUtils.createActionForm(RequestUtils.java:837), can you post the code that calls RequestUtils.createActionForm() as this where the exception is happening (actually if you have the Structs code, you could look in RequestUtils.java at line 837, and see what cast is being performed....)
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12074492
So, I guess you should have

  public class MyInitiativeBean extends ActionForm implements Comparable {  
      ...
  }

PS. You can ommit Serializable since ActionForm implements Serializable

0
 
LVL 1

Author Comment

by:haravallabhan
ID: 12074511
Cool zzynx u did it man...

That was it
I just extended the ActionForm in the Bean and ClassCast gone..(Ivan took it away)...:)

thanks a lot..

cjjclifford ,CEHJ I should thank you both also for your time... but zzynx deserved the points...

zzynx before giving you the points... I would like to ask how will you do reversing of sorting...

Collections.reverse?.... or is there any way there....

Thanks again
please reply to this
Hara
0
 
LVL 37

Accepted Solution

by:
zzynx earned 125 total points
ID: 12074530
>>Cool zzynx u did it man...
:°))


Reverse sorting is done by returning -1 where you now return 1 and vice versa

e.g.

         return ( reverse ? -1 : 1 );

instead of

         return 1;

and vice versa.
(with reverse being a boolean)
0
 
LVL 1

Author Comment

by:haravallabhan
ID: 12074657
cool...
Thanks

deserve more than this points..
Thanks

Hara
0
 
LVL 37

Expert Comment

by:zzynx
ID: 12074764
Thanks for accepting.

>> deserve more than this points..
Well, if you feel like that, you can always increment the points before accepting.


P.S.
If you still want to increment the points of this Q, you can
1) ask to reopen this question
by posting a zero-point question in http://www.experts-exchange.com/Community_Support/

Subject: Moderator Please Reopen
Body: Please reopen this question:
http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21133372.html

2) Once reopened by an operator you get a mail
3) Then you can increment the points ;°)
4) Then you can reaccept.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 12079434
>>zzynx before giving you the points... I would like to ask how will you do reversing of sorting...

>>
Reverse sorting is done by returning -1 where you now return 1 and vice versa

e.g.

         return ( reverse ? -1 : 1 );

instead of

         return 1;

and vice versa.
(with reverse being a boolean)
>>

There's no need to do that:



Collections.sort(list, Collections.reverseOrder());
   
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
PDFBox - convert image to PDF, PDF resolution 3 117
github account with ecipse 1 42
Java Timer (static) 9 36
javap bin 2 27
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now