首页 > 解决方案 > java.lang.ClassCastException:[Ljava.lang.Object;不能转换为 [Ljava.lang.Comparable; 即使类型应该相同

问题描述

我正在开发一个煎饼堆栈程序,该程序将创建一个煎饼堆栈并允许用户选择一个煎饼,该煎饼将从上面的煎饼中翻转堆栈。用户将执行此操作,直到按大小订购煎饼。(屏幕截图显示了它的外观) Pancake Stack Program

我在使用煎饼堆栈中的元素时遇到问题,得到 java.lang.ClassCastException: [Ljava.lang.Object; 无法转换为 [Ljava.lang.Comparable 错误。

我以为我已经将 PancakeStack 定义为仅保存可比较的 Pancake 对象,但似乎程序将堆栈中的所有内容视为不可比较的对象。

煎饼班

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;

/**
 *
 * @author leo-nard
 */
public class Pancake implements Comparable<Pancake>
{
    private Color colour;
    private int size;
    private int select;
    private Color ogColour;
    private int height = 20;
    
    public Pancake(int size, Color c)
    {
        this.size = size;
        this.colour = ogColour = c;
    }
  
    @Override
    public int compareTo(Pancake o) 
    {
        //find size of Pancake object which compareTo was called through
        int xSize = this.getSize();
        //find size of pancake we are comparing to (input parameter)
        int ySize = o.getSize();
        
        //print size difference as integer interpritation
        if(xSize > ySize)
        {
            return 1;
        }
        else if(xSize < ySize)
        {
            return -1;
        }
        else if(xSize == ySize)
            return 0;
        return 0;
    }
    
    public int getSize()
    {
        return size;
    }
    
    public void highlight(boolean selected)
    {
        if(selected)
            this.colour = Color.RED;
        if(!selected)
            this.colour = ogColour;
    }
    
    public void draw(Graphics g)
    {
        Graphics2D g2d = (Graphics2D) g;
        g2d.drawRoundRect(10, 50, 150, 150, 50, 30); // to draw a rounded rectangle.
    }

}

PancakeStack 类

import java.awt.Color;
import java.util.*;

/**
 *
 * @author leo-nard
 * @param <Pancake>
 */
public class PancakeStack<Pancake extends Comparable<Pancake>> extends ArrayStack<Pancake>
{
    
    public PancakeStack()
    {
        super();
        numElements = 0;
    }
    
    PancakeStack(Collection<? extends Pancake> c)
    {
        this();
        for(Pancake element:c)
        {
            push(element);
        }
    }
    
    public Pancake obtainPancake(int index)
    {
        if(isEmpty())
        {
            throw new NoSuchElementException("There are no Pancakes in the Stack.");
        }
        else if(index > numElements || index< 0)
            throw new NoSuchElementException("There are no Pancakes in the stack at this index.");
        
        Pancake p = elements[index]; 
        return p;
    }
    
    public int findMax(int i)
    {
        int index = 0;
        int max = 0;
        Iterator<Pancake> it = iterator();
        Pancake current = elements[i];
        Pancake largest = current;
        if(isEmpty())
            throw new NoSuchElementException("There are no Pancakes in the Stack");
        else
        {
            while(it.hasNext())
            {
                current = it.next();
                if(current.compareTo(largest) == 1 && index >= i)
                {
                    largest = current;
                    max = i;
                }
                else
                    index++;
            }

            return max;
        }
        
    }

PancakeGUI

import java.awt.BorderLayout;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

/**
 *
 * @author leo-nard
 */
public class PancakeGUI extends JPanel implements ActionListener
{
    private DrawPanel drawPanel;
    private JButton resetButton, resolveButton;
    private Pancake singlePancake;
    private PancakeStack<Pancake> stack;
    private Timer timer;
    
    
    public PancakeGUI()
    {
        super(new BorderLayout());
        
        stack  = new PancakeStack<Pancake>();
        
        JPanel southPanel = new JPanel();
        
        resetButton = new JButton("Reset");
        resetButton.addActionListener(this);
        southPanel.add(resetButton);
        
        resolveButton = new JButton("Resolve");
        resolveButton.addActionListener(this);
        southPanel.add(resolveButton);
        
        drawPanel = new DrawPanel();
        
        add(southPanel, BorderLayout.SOUTH);
        add(drawPanel, BorderLayout.NORTH);
        
        timer = new Timer(20, this);
        timer.start();
    }
    
    private class DrawPanel extends JPanel
    {
        public DrawPanel()
        {
            setBackground(Color.WHITE);  
            setPreferredSize(new Dimension(500,500));           
        }
        
        @Override
        public void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            Color c = new Color(255, 0, 0);
            Pancake p = new Pancake(10, c);
            stack.push(p);
            
            //pancake.draw(g);
            
        }
    } 
    
    @Override
    public void actionPerformed(ActionEvent e) 
    {
        
    }
    
    public static void main(String[] args) 
    {
        JFrame frame = new JFrame("Pancake Sort Problem");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(new PancakeGUI());
        frame.pack();
        // position the frame in the middle of the screen
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension screenDimension = tk.getScreenSize();
        Dimension frameDimension = frame.getSize();
        frame.setLocation((screenDimension.width-frameDimension.width)/2,
           (screenDimension.height-frameDimension.height)/2);
        frame.setVisible(true);
        
        //Something while the main thread is still alive
        for (int i=0; i<20; i++)
        {  System.out.println("Main thread counting: " + i);
           try
           {  
               Thread.sleep(500); // delay for 500ms
           }
           catch (InterruptedException e)
           {}
        }
        
        PancakeStack<Pancake> stack = new PancakeStack<Pancake>();
        System.out.println(stack.getClass());
        Color c = new Color(255, 0, 0);
        Pancake p1 = new Pancake(1, c);
        Pancake p2 = new Pancake(2, c);
        Pancake p3 = new Pancake(3, c);
        Pancake p4 = new Pancake(4, c);
        Pancake p5 = new Pancake(5, c);
        Pancake p6 = new Pancake(6, c);
        Pancake p7 = new Pancake(7, c);
        Pancake p8 = new Pancake(8, c);
        Pancake p9 = new Pancake(9, c);
        Pancake p10 = new Pancake(10, c);
        Object p11 = new Pancake(11, c);
        stack.push(p3);
        stack.push(p7);
        stack.push(p6);
        stack.push(p10);
        stack.push(p5);
        stack.push(p9);
        stack.push(p2);
        stack.push(p8);
        stack.push(p4);
        System.out.println(stack.obtainPancake(2));
    }

   
}

数组栈

import java.util.Collection;
import java.util.NoSuchElementException;

public class ArrayStack<E> implements StackADT<E>
{
   private final int INITIAL_CAPACITY = 20;
   protected int numElements;
   protected E[] elements;
   
   // default constructor that creates a new stack 
   // that is initially empty
   public ArrayStack()
   {  numElements = 0;
      elements = (E[])(new Object[INITIAL_CAPACITY]); // unchecked
   }
   
   // constructor for creating a new stack which
   // initially holds the elements in the collection c
   public ArrayStack(Collection<? extends E> c)
   {  this();
      for (E element : c)
         push(element);
   }

   // Adds one element to the top of this stack
   public void push(E element)
   {  if (numElements >= elements.length)
         expandCapacity();
      elements[numElements++] = element;
   }
   
   // removes and returns the top element from this stack
   public E pop() throws NoSuchElementException
   {  if (numElements > 0)
      {  E topElement = elements[numElements-1];
         elements[numElements-1] = null;
         numElements--;
         return topElement;
      }
      else
         throw new NoSuchElementException();
   }
   
   // returns without removing the top element of this stack
   public E peek() throws NoSuchElementException
   {  if (numElements > 0)
         return elements[numElements-1];
      else
         throw new NoSuchElementException();
   }
   
   // returns true if this stack contains no elements
   public boolean isEmpty()
   {  
       return (numElements==0);
   }
   
   // returns the number of elements in this stack
   public int size()
   {  
       return numElements;
   }
   
   // returns a string representation of the stack from top to bottom
   public String toString()
   {  
       String output = "[";
      for (int i=numElements-1; i>=0; i--)
      {  output += elements[i];
         if (i>0)
            output += ",";
      }
      output += "]";
      return output;
   }
      
   // helper method which doubles the current size of the array
   private void expandCapacity()
   {  
       E[] largerArray =(E[])(new Object[elements.length*2]);//unchecked
      // copy the elements array to the largerArray
      for (int i=0; i<numElements; i++)
         largerArray[i] = elements[i];
      elements = largerArray;
   }
}

错误发生在 PancakeStack 第 43 行 - Pancake p = elements[index]; 我正在尝试将堆栈中的煎饼分配给另一个煎饼变量

标签: javaruntime-errorsubclasscomparable

解决方案


推荐阅读