English 中文(简体)
关于阵容概念
原标题:Regarding arrays concept
  • 时间:2012-05-05 05:34:24
  •  标签:
  • java
  • arrays

我正在寻求咨询意见,因为我操作以下法典时有错误:

public class Test9 {


    public static void main(String[] args) {        

        Object [] myObjects = {
                 new Integer(12),
                 new String("foo"),
                 new Integer(5),
                 new Boolean(true)
                 };
                 Arrays.sort(myObjects);
                 for(int i=0; i<myObjects.length; i++) {
                 System.out.print(myObjects[i].toString());
                 //System.out.print(" ");
                 }

    }

}

我发现的错误是:

   Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
    at java.lang.Integer.compareTo(Unknown Source)
    at java.util.Arrays.mergeSort(Unknown Source)
    at java.util.Arrays.sort(Unknown Source)
    at Practicequestions.Test9.main(Test9.java:18)
最佳回答
 Object [] myObjects = {
                 new Integer(12),
                 new String("foo"),
                 new Integer(5),
                 new Boolean(true)
                 };

这种通用式阵列。 因此,当你试图用<代码>公开静态无效(目标a)加以分类时,该编码可操作时间。 甲型六氯环己烷引起阵列含有不能相互比较的内容。

Array.sort() specified array of objects into ascending order, according to the natural ordering of its elements. There is a another method you can use it sort(Object[] a,Comparator c) . Implement Comparator with your own logic and pass it.

Object[] myObjects = { new Integer(12), new String("foo"),
                new Integer(5), new Boolean(true) };
        Comparator<Object> comparator=new Comparator<Object>() {
            @Override
            public int compare(Object obj1, Object obj2) {
                if(obj1 instanceof String && obj2 instanceof String){
                    return String.valueOf(obj1).compareTo(String.valueOf(obj2));
                }else if(obj1 instanceof Integer && obj2 instanceof Integer){
                    return ((Integer) obj1).compareTo((Integer) obj2);
                }else if(obj1 instanceof Boolean && obj2 instanceof Boolean){
                    return ((Boolean) obj1).compareTo((Boolean) obj2);
                }else if(obj1 instanceof String && obj2 instanceof Integer){
                    return 1;
                }else if(obj1 instanceof Integer && obj2 instanceof String){
                    return -1;
                }else if(obj1 instanceof Boolean){
                    return -1;
                }else if( obj2 instanceof Boolean){
                    return 1;
                }
                return 0;
            }
        }; 
        Arrays.sort(myObjects,comparator);
        for (int i = 0; i < myObjects.length; i++) {
            System.out.print(myObjects[i].toString());
        }
问题回答

我确实认为,你面临的问题源自您在座标上的<条码>。

这样就将尝试compare物体,但所张贴的类型无法做到。 比较两个愤怒、扼杀和ool是否合理? 它们不能分类,至少没有习惯比较器。

替换<代码>String和Boolean,改为Integer

EDIT:用粗体、不准确的措辞。 这些物体从未投放。 对比图的功能对它们进行了比较。

准时将你的物体自动转换为同一类型。 您在把物体添加到收集中之前,必须投下你的物体。

Object [] myObjects = { 
                 new Integer(12).toString(), 
                 new String("foo"), 
                 new Integer(5).toString(), 
                 new Boolean(true).toString() 
                 }; 
Arrays.sort(myObjects); 
for(int i=0; i<myObjects.length; i++) { 
                 System.out.print(myObjects[i].toString()); 
                 //System.out.print(" "); 
} 

当然,我认为这是一个理论问题,你的目标应该已经产生并储存在一些变数中。

回答你的问题完全是 st。

<代码>Arrays.sort()要求阵列中的所有内容均实施<代码>Comparable,并援引compareTo()方法对阵列进行分类。

<compareTo() in the Integer的类别中,如果与not 另一 Integer相比,该物体将产生例外情形。

The Arrays.sort() method does NOT try to "cast objects to the same type" as other answers have suggested. The cast exception occurs because the compareTo() of Integer is typed, but the invocation from Arrays.sort() is not typed.

The sort(Object[]) method is assuming that every object in the array implements Comparable, and using that method to compare the elements. When it tries to compare (for instance) the first and second elements, it calls Integer.compareTo(Object) with a String argument. The Integer.compareTo(Object) tries to cast the argument to an Integer, and that (naturally) fails, giving a ClassCastException.

底线是,除非:

  • the array elements are non-null,
  • the array elements all implement Comparable, and
  • all of the elements compareTo() methods can cope with the types of all of the other elements.

In this case, the last is not true. The compareTo method of Integer only understands other Integer instances, and the compareTo method of String only understands other String instances.

如果上述任何前提条件都得不到满足,则需要使用<代码>Arrays.sort([],比较]方法,并提供<代码>Comparator,该编码为您阵列的所有要素服务。


Incidentally, this illustrates why arrays and collections of mixed types are generally a bad idea. It is awkward to deal with a bunch of different things when you don t know what their types are going to be,.





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签