Java:整数 obj 无法转换为 Comparable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2112343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 19:31:31  来源:igfitidea点击:

Java: Integer obj can't cast to Comparable

javageneric-programmingcomparable

提问by TLM

I'm having problems trying to pass an Integer object from a driver class as an argument for function of a SortedArray Generic class I created. From my driver class, I convert the user's int input into an Integer object to be cast onto Comparable of my SortedArray class.

我在尝试将驱动程序类中的 Integer 对象作为我创建的 SortedArray 通用类的函数的参数传递时遇到问题。在我的驱动程序类中,我将用户的 int 输入转换为一个 Integer 对象,以转换到我的 SortedArray 类的 Comparable 上。

I continue to receive the error: "Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to Comparable". I took a look at some of my classmates' source codes only to find little difference in setting the arguments/parameters yet they have their code working just fine. I've been looking for hours trying to find what error I've made and I still can't find why my Integer object can't be cast to Comparable.

我继续收到错误消息:“线程“main”中的异常 java.lang.ClassCastException: java.lang.Integer cannot be cast to Comparable”。我查看了一些同学的源代码,发现在设置参数/参数方面几乎没有区别,但他们的代码运行良好。我一直在寻找几个小时试图找出我犯了什么错误,但我仍然找不到为什么我的 Integer 对象不能转换为 Comparable。

Here's a bit from my SortedArray Class

这是我的 SortedArray 类中的一些内容

public class SortedArray implements Comparable{
    public int size;
public int increment;
public int top;
    Comparable[] a = new Comparable [size];

public SortedArray(int initialSize, int incrementAmount)
{
        top = -1;
        size = initialSize;
        increment = incrementAmount;

}
public int appropriatePosition(Comparable value)
{
        int hold = 0;
        if(top == -1)
        {
            return 0;
        }
        else
        {    
            for(int i = 0; i <= top; i++)
            {
                if(a[i].compareTo(value) > 0)
                {
                    hold = i;
                    break;
                }
            }
        }
        return hold;
}

public void insert(Comparable value) //The function that my driver class needs to access
{
        //Shifting numbers to the top
        if(full() == true)
        {
            Comparable[] tempArray = new Comparable[top + increment];
            for(int i= 0; i< size; i++)
            {
                tempArray[i]= a[i];
                a  = tempArray;
            }
            size = top + increment;
        }
        if(a[appropriatePosition(value) + 1] != null)
        {
            for(int i = top; i < appropriatePosition(value); i--)
            {
                a[i + 1] = a[i];
            }
        }
        a[appropriatePosition(value) + 1]= value;
    }

Here's the code for my driver class that passes Integer Object insertObj as an argument for SortedArray's insert function.

这是我的驱动程序类的代码,它将整数对象 insertObj 作为 SortedArray 插入函数的参数传递。

public class IntDriver  {
 public static void main(String[] args)
 {
     Scanner keyboard = new Scanner(System.in);
     //Creating variables
     int data;
     boolean check = false;
     int choice;
     int size = 5;
     int increment = 3;
     SortedArray b = new SortedArray(size, increment);
     //Creating Menu
     while(check == false)
     {
     System.out.println("Please choose through options 1-6.");
     System.out.println("1. Insert\n2. Delete\n3. Clear\n4. Smallest\n5. Largest\n6. Exit");
     choice = keyboard.nextInt();
     switch(choice)
         {
         case 1:
             System.out.println("Type the int data to store in array location.");
             data = keyboard.nextInt();
             Integer insertObj = new Integer(data);
             b.insert(insertObj);// Here's where I lay "insertObj" as an argument for the SortedArray function.
             System.out.println("The value " + data + " is inserted");
            break;

回答by axtavt

The problem is that Integerextends java.lang.Comparable, then your Comparableis not a java.lang.Comparable. Look at the error message, your Comparablecomes from the default package rather than java.lang:

问题是Integer扩展java.lang.Comparable,那么你Comparable的不是java.lang.Comparable. 查看错误消息,您Comparable来自默认包而不是java.lang

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to Comparable

That is, you can't cast java.lang.Integerto your own class

也就是说,你不能投射java.lang.Integer到你自己的班级

回答by Paul Wagland

As mentioned by axtavt, the problem is that you have your own class Comparable. More specifically, what that means is that:

正如axtavt所提到的,问题在于您有自己的类 Comparable。更具体地说,这意味着:

Integer.valueOf(1) instanceof java.util.Comparable == true
Integer.valueOf(1) instanceof Comparable == false

This means that somewhere in your code you have something like:

这意味着在你的代码中的某个地方你有这样的东西:

Object[] a = new Object[] {Integer.valueOf(1);};
Comparable x = (Comparable) a[0];
// or something equivalent, this is likely being passed through layers
// and not being done next to each other like this.

You need to change that to:

您需要将其更改为:

Object[] a = new Object[] {Integer.valueOf(1);};
java.util.Comparable x = (java.util.Comparable) a[0];

Even better, you should rename your Comparator class to something that doesn't collide with the standard classes in Java. In general, even though Java has namespacing, you should try to avoid your classes having the same name as the system classes to avoid exactly this kind of confusion.

更好的是,您应该将 Comparator 类重命名为与 Java 中的标准类不冲突的名称。通常,即使 Java 具有命名空间,您也应该尽量避免您的类与系统类具有相同的名称,以避免这种混淆。

回答by Powerlord

I haven't put too much effort into this, but wouldn't it just be easier to use a SortedSetimplementation (or its child interface NavigableSet) like TreeSetrather than write your own class? That is, unless you wanted duplicate elements...

我没有为此付出太多努力,但是使用SortedSet实现(或其子接口NavigableSetTreeSet比编写自己的类更容易吗?也就是说,除非你想要重复的元素......