配列やArrayListには、前の要素を参照している場合はどうすればtrueを返す関数を実装することができますか?

RShome:

曲のいずれかが、プレイリストの前の曲への参照が含まれている場合プレイリストは繰り返しプレイリストと考えられています。それ以外の場合は、プレイリストはヌルを指す最後の曲で終了します。

私はそれがない場合は、関数のプレイリストを繰り返している場合は、trueを返すことisRepeatingPlaylistまたは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());

繰り返しますが、これは私が概念をプログラミングに関する理論を読んだとき、私はほとんど理解することができますので、私はコーディングの課題をやって、宿題の練習ではありませんが、私が開始するには、または適用する方法がわからないプログラムを書くに直面したとき。

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();
    }
}
エンリケサビノ:

私はこれかもしれないが仕事だと思います。

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

編集1:この回答のコメントで述べたように、==それは比較ので、いくつかのケースでは最高ではないかもしれないメモリ位置の各オブジェクトのを。この問題を解決するために、メソッドの実装ではhashCode()equals()あなたは彼らが何であるかわからない場合は、推奨されている、読んでみてくださいこれを

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=187730&siteId=1