如果 array 或 arrayList 引用了前一个元素,我如何实现一个返回 true 的函数?

RSh*_*ome 6 java arrays arraylist

如果任何歌曲包含对播放列表中上一首歌曲的引用,则该播放列表被视为重复播放列表。否则,播放列表将以指向空的最后一首歌曲结束。

我需要实现一个函数 isRepeatingPlaylist,如果播放列表重复,则返回 true,否则返回 false。

例如,以下代码打印“true”,因为两首歌曲都指向对方。

Song first = new Song("Hello");
Song second = new Song("Eye of the tiger");    
first.setNextSong(second);
second.setNextSong(first);    
System.out.println(first.isRepeatingPlaylist());
Run Code Online (Sandbox Code Playgroud)

再说一遍,这不是作业练习,我在做编码挑战,因为当我阅读有关编程概念的理论时,我几乎可以理解,但是当面临编写程序时,我不知道从哪里开始,也不知道如何应用。

public class Song {

    private String name;
    private Song nextSong;

    public Song(String name) {
        this.name = name;
    }

    public void setNextSong(Song nextSong) {
        this.nextSong = nextSong;
    }

    public boolean isRepeatingPlaylist() {
        //throw new UnsupportedOperationException("Waiting to be implemented.");
        List<String> list = new ArrayList<String>();
        list.add(one);
        list.add(two);
        list.add(three);
        list.add(four);

        if list.contains()
        return true;
        else
            return false;

    }

    public static void main(String[] args) {
        Song first = new Song("Hello");
        Song second = new Song("Eye of the tiger");
        Song third = new Song("a test");
        Song fourth = new Song("survivor");

        first.setNextSong(second);
        second.setNextSong(first);

        System.out.println(first.isRepeatingPlaylist();
    }
}
Run Code Online (Sandbox Code Playgroud)

Hen*_*ino 1

我认为这可能有效:

public boolean isRepeatingPlaylist() 
{
    Set<Song> songs = new HashSet<Song>();
    songs.add(this);
    Song current = this.getNextSong();
    //if you did not implment a getter for the nextSong property I think you should
    while (current.getNextSong() != null && !songs.contains(current.getNextsong())) {

        songs.add(current);
        current = current.getNextSong();
    }

    return songs.contains(current.getNextsong()); 
}
Run Code Online (Sandbox Code Playgroud)

编辑1:正如这个答案的评论中提到的,==在某些情况下可能不是最好的,因为它比较每个对象的内存位置。为了解决此问题,请实施方法hashCode()equals()建议,如果您不知道它们是什么,请尝试阅读