How can I implement a function to return true if array or arrayList refers to a previous element?

RShome :

A playlist is considered a repeating playlist if any of the songs contain a reference to a previous song in the playlist. Otherwise, the playlist will end with the last song which points to null.

I need to Implement a function isRepeatingPlaylist that, returns true if a playlist is repeating or false if it is not.

For example, the following code prints "true" as both songs point to each other.

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

Again, this is not a homework exercise, I am doing coding challenges because when I read theory about programming concepts, I can almost understand, but when faced with writing a program I don't know where to start, or how to apply.

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();
    }
}
Henrique Sabino :

I think this might work:

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()); 
}

Edit 1: As mentioned in the comments of this answer, the == in some cases might not be the best because it compares the memory location of each object. In order to fix this issue, implementing the methods hashCode() and equals() are recommended, if you don't know what they are, try reading this.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=77533&siteId=1