Topic: java.lang.ClassCastException

  Print this page

1.java.lang.ClassCastException Copy to clipboard
Posted by: AchillesA
Posted on: 2004-09-07 16:34


import java.util.*;
import com.bruceeckel.util.*;
class E_13_2 implements Comparator
{
private String s1;
private String s2;
private E_13_2 e;
E_13_2(String s1,String s2){
this.s1=s1;
this.s2=s2;
}
public boolean equals(Object o){
return (o instanceof E_13_2)&&(s2==((E_13_2)o).s2);
}
public int compare(Object o1,Object o2){
String s3=((E_13_2)o1).s2, s4=((E_13_2)o2).s2;
return e.compare(s3,s4);
}
public String toString(){
return "[s1:"+s1+"<>s2:"+s2+"]";
}
public static Arrays2.RandStringGenerator gen=
new Arrays2.RandStringGenerator(8);
public static Generator generator(){
return new Generator(){
public Object next(){
return new E_13_2((String)gen.next(),(String)gen.next());
}
};
}
}
public class E13Test
{
public static void main(String args[]){
E_13_2[] e13 = new E_13_2[10];
Arrays2.fill(e13,E_13_2.generator());
Arrays2.print("before sort() =>",e13);
Arrays.sort(e13);
Arrays2.print("after sort() =>",e13);
}
}

+-----------output----------------+

before sort() => ([s1:dmOmrMCG<>s2:tuMsnVcf], [s1:CbWECTsI<>s2:AzTHfIcq], [s1:QASdXyRN<>s2:ydUhgXBj], [s1:jWLThZNP<>s2:pJnyGKiG], [s1:aqXwNAWq<>s2:dNmVZbuQ], [s1:KxKLcEQd<>s2:VIiAZiIt], [s1:ycDvsmYR<>s2:sBMFozNq], [s1:fbfcKGnd<>s2:tGEchRKv], [s1:wvQmPgJh<>s2:fJEDWkcG], [s1:FfaksBZv<>s2:lnhSLecY])
java.lang.ClassCastException
at java.util.Arrays.mergeSort(Arrays.java:1152)
at java.util.Arrays.mergeSort(Arrays.java:1163)
at java.util.Arrays.sort(Arrays.java:1079)
at E13Test.main(E13Test.java:38)
Exception in thread "main"
输出完成 (耗时 0 秒) - 正常终止

我是哪里出错了,该怎样改啊?

2.Re:java.lang.ClassCastException [Re: AchillesA] Copy to clipboard
Posted by: cxp108
Posted on: 2004-09-07 17:10

问题很可能出在

public int compare(Object o1,Object o2){
String s3=((E_13_2)o1).s2, s4=((E_13_2)o2).s2;
return e.compare(s3,s4);
}

e 本身是个E_13_2的实例,compare本身是E_13_2类的方法

该函数实际上是在调用自己,应该是个死循环才对.

但你将两个String 导入compare中,又要将其强制转型成E_13_2的类型

因此在main线程中出现了未捕捉的异常,于是main线程中断了,程序就退

出了,否则该程序应该会在Arrays.sort(e13);的时候卡死

3.Re:java.lang.ClassCastException [Re: AchillesA] Copy to clipboard
Posted by: AchillesA
Posted on: 2004-09-08 20:34

但是我现在改成这样:

public int compare(Object o1,Object o2);
String s3=((E_13_2)o1).s2,s4=((E_13_2)o2).s2;
return s3.compareTo(s4);
}

上面我改用s3.compareTo(s4);(调用String的compareTo())为什么还是出现同样的错误。
+--------------------+
我究竟该怎样改呢?


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923