java.lang.ClassCastException in Arrays.sort call though implementing Comparable -
i trying sort array of rectangles using arrays.sort
. class rectangle
implements comparable<rectangle>
, have overridden compareto()
method. these 2 classes: rectangle , 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); (rectangle x : rectangles) { system.out.println(x.getperimeter()); } arrays.sort(rectangles); }
however, keep getting error message:
exception in thread "main" java.lang.classcastexception: rectangle cannot cast java.lang.comparable.
can me see i'm doing wrong?
exception in thread "main" java.lang.classcastexception: rectangle cannot cast java.lang.comparable.
possibly version of rectangle in main class not comparable. make sure class rectagle refering 1 shown above.
make sure build class correctly. suggest using ide build classes , doing clean build should fix this.
Comments
Post a Comment