I have two classes, one of them having as an attribute the other. The first class is called Coordinate, and it has a letter and a number as attributes (so, something like A4), and the other is CarSpace.
This is the compareTo method of Coordinate:
<pre> public int compareTo (Object obj) {
char zona = ((Coordinate)obj).zone;//////////////
int comparetozona = Character.compare(zone, zona); //0 SI SON IGUALES, <0 SI EL PRIMERO ES MENOR QUE EL SEGUNDO, >0 EN EL CASO OPUESTO
if (comparetozona < 0) {return -1;} //SI EL RESULTADO PREVIO ES <0, ENTONCES EL OBJETO QUE INVOCA AL METODO ES MENOR QUE EL QUE SE LE PASA A LA FUNCION
else if (comparetozona > 0) {return 1;}
else {
if (this.number < (((Coordinate)obj).number)) {return -1;}
else if (this.number > (((Coordinate)obj).number)) {return 1;}
else {return 0;}
}
}
Here I am comparing the letters first, and if the letters are equal, the numbers.
Then I have the compareTo method of CarSpace:
public int compareTo (Object obj) {
int comp = this.coordinate.compareTo(obj);
if (comp < 0) {return -1;}
else if (comp > 0) {return 1;}
else {return 0;}
}
CarSpace has more multiple attributes, but I only need to compare the Coordinate attribute to know which has is higher or lower. The problem is that Im getting a runtime error on this line:
int comp = this.coordinate.compareTo(obj);
and here:
char zona = ((Coordinate)obj).zone;
The error is as follows:
Quote:
Exception in thread "main" java.lang.ClassCastException: class P5.CarSpace cannot be cast to class P5.Coordinate (P5.CarSpace and P5.Coordinate are in unnamed module of loader 'app')
at P5.Coordinate.compareTo(Coordinate.java:46)
at P5.CarSpace.compareTo(CarSpace.java:39)
at java.base/java.util.TreeMap.compare(TreeMap.java:1291)
at java.base/java.util.TreeMap.put(TreeMap.java:536)
at java.base/java.util.TreeSet.add(TreeSet.java:255)
at P5.Parking.<init>(Parking.java:55)
at P5.P5b.main(P5b.java:16)
But I dont see where Im supposed to be doing this CarSpace cast into Coordinate that the virtual machine complains about.
What I have tried:
I thought that maybe the problem was on my equals method, since its the only place where I see doing a CarSpace cast, but unless Im mistaken, compareTo method and equals are completely unrelated. These are the equals method in case Im wrong and they are actually needed:
public boolean equals (Object obj) {
if (plate.equals(((CarSpace)obj).getPlate()) && coordinate.equals(((CarSpace)obj).getCoordinate())) {return true;}
else {return false;}
}
Equals for CarSpace
public boolean equals(Coordinate c) {
boolean coordenada = this.equals(c);
if (coordenada == true) {
return true;
}else{return false;}
}
equals for Coordinate class