【问题标题】:how to make a connected list of elements in Java如何在Java中制作元素的连接列表
【发布时间】:2014-06-25 23:51:17
【问题描述】:

我想创建一个学生元素的连接列表。 Student 类必须只有两个字段(名称和代码编号)。我还创建了一个比较名称的方法,如果名称相等,那么我比较代码编号。这是因为我必须从低到高插入元素。 我创建了一个类:

class Student
    private String name;
    private int codeNumber;

    public Student(String name, int AM){
        this.name = name;
        this.codeNumber = codeNumber;
    }

    public int compareTo(Student other){
        int result;
        if(other.name.compareTo(this.name) == 0){
            result = 0;
            return result;
        }
        if(other.name.compareTo(this.name) < 0){
            result = 1;
            return result;
        }
        if(other.name.compareTo(this.name) > 0){
            result = -1;
            return result;
        }
        if(other.codeNumber > this.codeNumber){
            result = 1;
            return result;
        }
        if(other.codeNumber < this.codeNumber){
            result = -1;
            return result;
        }
    }

    public String getName(){
        return name;
    }

    public int getcodeNumber(){
        return codeNumber;
    }   
}

这就是问题所在。我需要一个 StudentList 类来制作我自己的列表。 所以我创建了这个类,但我不确定我在这个类中是否有正确的字段。 我创建了 4 个字段: 1.private Student学生元素; 2.private StudentList next = null;对下一个元素的引用 3.private StudenList head;对列表开头的引用 4.private int size = 0;知道元素的数量 这是我的代码:

class StudentList{
    private Student studentElement;
    private StudentList next = null;
    private StudentList head;
    private int size = 0;

    public StudentList(Student listEl){
        listElement = listEl;
    }

        public boolean containsElement(Student p){
        StudentList position = head;
        while(position != null){
            if(StudentElement.getName().equals(p.getName()) && studentElement.getAM() == p.getAM()){
                return true;
            }
            position = position.getNext();
        }
        return false;
    }

}

这是我的代码。谁能告诉我我的班级是否有正确类型的字段并帮助我创建插入方法。

【问题讨论】:

    标签: java list class sorting connection


    【解决方案1】:

    不要重新发明轮子。

    更喜欢使用java.util.LinkedList

    并以您需要的方式添加Student 实例。这将保留顺序 您将其添加到列表中

    【讨论】:

    • 是的,我知道,但我必须自己制作列表,所以我不能使用 LinkedList
    【解决方案2】:

    使用 Java 库列表实现之一,例如 ArrayListLinkedList,它们完全按照您的意愿行事,没有必要自行滚动。

    如果需要,还可以了解Collections.sort()

    您的Student 类还应该实现Comparable 接口,该接口(幸运的是)与您现有的compareTo 方法具有相同的签名。

    【讨论】:

    • 是的,我知道 ArrayList,但在我的练习中,我必须创建自己的列表。
    猜你喜欢
    • 1970-01-01
    • 2014-04-18
    • 2021-12-03
    • 2014-01-11
    • 1970-01-01
    • 2013-11-02
    • 2011-08-16
    • 2015-03-23
    • 1970-01-01
    相关资源
    最近更新 更多