here is a question I wanted to solve:
https://www.testdome.com/questions/java/song/88836
I came across a solution, however I am having trouble understanding part of it. Specifically, this snippet of code:
Song song1 = this;
Song song2 = this;
I have never seen the this keyword used like this. If someone can help me understand, it would be much appreciated.
public Song(String name) {
this.name = name;
}
public void setNextSong(Song nextSong) {
this.nextSong = nextSong;
}
public boolean isInRepeatingPlaylist() {
Song song1 = this;
Song song2 = this;
while (song2 != null && song2.nextSong != null) {
song1 = song1.nextSong;
song2 = song2.nextSong.nextSong;
if (song1 == song2) {
return true;
}
}
return false;
}
public static void main(String[] args) {
Song first = new Song("Hello");
Song second = new Song("Eye of the tiger");
first.setNextSong(second);
second.setNextSong(first);
System.out.println(first.isInRepeatingPlaylist());
}
}
New contributor
Emanuel Risk is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.