CompareTo 方法:返回类型:GREATER、EQUAL、LESS

问题描述 投票:0回答:1

我收到以下 4 个错误: character expected errors character expected errors 我正在做一个 LinkedList java 项目,需要实现 CompareTo 方法。我对 Java 很生疏,希望得到一些帮助来了解我在这个实现方面做错了什么。我应该使用整数而不是枚举吗? 我应该使用 switch/case/break 而不是 if/else 吗?

这是我的 ItemType 类的 Java 类文件

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
    //}
}

这是使用 ItemType 类方法compareTo() 的 SortedLinkedList.java 类的示例

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;
            }
}
java class singly-linked-list compareto sortedlist
1个回答
0
投票

您使用关键字

enum
作为返回类型而不是枚举本身,这就是您收到错误消息的原因:

public Comparison compareTo(ItemType item)
© www.soinside.com 2019 - 2024. All rights reserved.