使用compareTo方法与LinkedList按字母顺序添加对象

时间:2015-04-17 07:47:56

标签: java linked-list compareto

我创建了自己的LinkedList,其中包含一个Song对象(标题,艺术家等等)。我正在尝试添加一个用户输入歌曲详细信息的功能,并通过ARTIST按字母顺序将歌曲添加到列表中。我的问题是,我不知道如何设置if else语句,以便艺术家按字母顺序将其添加到列表中,提前感谢。

歌曲课程中的compareTo()

//Should return negative if in order, positive if out of order, 0 if equal
public int compareTo(Song s) {
        return title.compareTo(s.getTitle()); //I think this is correct?
}

主要类

public static void addSong(LinkedList list){
    Scanner input = new Scanner(System.in);

    System.out.println("Enter song title: ");
    String title = input.nextLine();
    System.out.println("Enter song artist: ");
    String artist = input.nextLine();
    System.out.println("Enter song album: ");
    String album = input.nextLine();
    System.out.println("Enter song length: ");
    String length = input.nextLine();

    Song songInfo = new Song(title, artist, album, length);
    for (int i = 0; i < list.size(); i ++){
        if ( //compareTo should be used here < 0 ){
        }else if( //compareTo should be used here == 0)

    }

LinkedList类添加方法

public class LinkedList {
private Node first;
private Node last;
public LinkedList(){
    first = null;
    last = null;
}
public boolean isEmpty(){
    return first == null;
}
public void add( Song c ){
    if( isEmpty() ) {
        first = new Node(c);
        last = first;
    }else{
        Node n = new Node(c);
        last.setNext(n);
        last = n;
    }
}

节点类

public class Node {
private Song song;
private Node next;
public Node( Song s ){
    song = s;
    next = null;
}
public Node( Song s, Node n ){
    song = s;
    next = n;
}
public Node getNext(){
    return next;
}
public void setNext(Node n){
    next = n;
}
public Song getValue(){
    return song;
}
public void setValue( Song s ){
    song = s;
}

0 个答案:

没有答案