java.lang.ClassCastException in Arrays.sort call though implementing Comparable

时间:2016-02-03 03:02:21

标签: java comparable

I am trying to sort an array of Rectangles using Arrays.sort. The class Rectangle implements Comparable<Rectangle> and I have overridden the compareTo() method. These are the two classes: Rectangle and the tester class.

public class Rectangle implements Comparable<Rectangle> {

  private int length;
  private int width;

  public Rectangle(int length, int width) {
    this.length = length;
    this.width = width;
  }

  public int getLength() {
    return length;
  }

  public int getWidth() {
    return width;
  }

  public int getPerimeter() {
    return (2*length) + (2*width);
  }

  public int compareTo(Rectangle x) {
    int p2 = ((Rectangle)x).getPerimeter();
    return this.getPerimeter()-p2;
  }

  public String toString() {
    return "Perimeter: " + this.getPerimeter();
  }
}

import java.util.*;
public class Test {

public static void main(String[] args) {

  Rectangle[] rectangles = new Rectangle[4];
  rectangles[0] = new Rectangle(3, 4);
  rectangles[1] = new Rectangle(2, 6);
  rectangles[2] = new Rectangle(2, 2);
  rectangles[3] = new Rectangle(1, 1);

  for (Rectangle x : rectangles) {
    System.out.println(x.getPerimeter());
  }

  Arrays.sort(rectangles);
}

However, I keep getting an error message:

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

Can someone help me see what I'm doing wrong?

1 个答案:

答案 0 :(得分:0)

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

Possibly your version of Rectangle that is in main class is not comparable. Make sure the class Rectagle you are refering is the one you shown above.

Make sure you build the class correctly. I suggest using an IDE to build you classes and doing a clean build should fix this.