I'm receiving these 4 errors: character expected errors character expected errors I'm doing a LinkedList java project that requires the implementation of the CompareTo method. I am rusty on Java and would like some help regarding what I am doing wrong regarding this implementaion. Should I use integers instead of enums? Should I use switch/case/break instead of if/else?
Here's my Java class file for class ItemType
import java.util.Objects;
public class ItemType {
private int value;
public ItemType() {
// Constructor body can be empty if there's no initialization code needed
}
public enum compareTo(ItemType item) {
if (this.getValue() < item.getValue()) {
return LESS;
} else if (this.getValue() > item.getValue()) {
return GREATER;
} else {
return EQUAL;
}
}
public int getValue() {
return value;
}
public void initialize(int num) {
value = num;
}
// Assuming Comparison is an enum, you would also need to define it in Java
//public enum Comparison {
//LESS,
//GREATER,
//EQUAL
//}
}
Here's an example of the SortedLinkedList.java class using the ItemType class method compareTo()
while (location.next != null && brake == 0) {
switch (item_.compareTo(location.item)) {
case ItemType.GREATER:
preLoc = location;
location = location.next;
break;
case ItemType.EQUAL:
System.out.println("\nError: Duplication\n");
return;
case ItemType.LESS:
brake = 1;
break;
}
}
You actually do not need your enum. Try to implement Comparable interface. You can take a look how to do it here.
Then rework your switch case to work with integer like:
switch (item_.compareTo(location.item)) {
case 1:
preLoc = location;
location = location.next;
break;
case 0:
System.out.println("\nError: Duplication\n");
return;
case -1:
brake = 1;
break;
}
Happy coding!
UPD
Example how to implement (be aware it is not final version and you can provide your own implementation):
public class ItemType implements Comparable<ItemType> {
private int value;
public ItemType() {
// Constructor body can be empty if there's no initialization code needed
}
@Override
public int compareTo(ItemType o) {
if (this.value > o.value) {
return 1;
}
if (this.value == o.value) {
return 0;
}
return -1;
}
}