2017-10-18 81 views
0

我提出的Android应用程序的其他一个ArrayList的一部分。我试图猜测用户刚刚在木琴上演奏了哪首歌。我有:private List<String> mDespacito = new ArrayList<String>(Arrays.asList("f", "a","d","d"));private List<String> mPlayed = new ArrayList<String>();当用户按下木琴一个关键,我加他压到mPlayed ArrayList中的关键,是这样的:Java是为了

public void playD(View v){ 
    Log.d("Xylophone", "Played D!"); 
    mSoundPool.play(mDSoundId,LEFT_VOLUME,RIGHT_VOLUME,PRIORITY,NO_LOOP,NORMAL_PLAY_RATE); 
    mPlayed.add("d"); 
    CheckForSong(); 

}

现在,CheckForSong包含:

public void CheckForSong(){ 
    if (mPlayed.containsAll(mDespacito)){ 
     Log.d("Xylophone","You just played despacito"); 
     mPlayed.removeAll(mDespacito); 
    } 
} 

所以,它应该做的:

played F 
played A 
played D 
played D 
You just played despacito 

但它的作用:

played F 
played A 
played D 
You just played despacito 
played D 

你甚至可以这样做:

played F 
played G 
played A 
played G 
played D 
You just played despacito 

而且我知道为什么:因为if (mPlayed.containsAll(mDespacito))的只是检查是否mDespacito的元素是mPlayed。但我需要检查是否有mDespacito的所有元素(包括那些有两次),如果他们在正确的顺序。有没有像我可以使用的命令?由于

+1

'Collections.indexOfSubList'可以帮助你! –

+0

如果处理个人笔记,这将得到串连成一个字符串中的字符,你可以使用'String.contains()'这需要顺序考虑。 –

回答

1

Collections.indexOfSubList就是答案。我用这样的:

public void CheckForSong(){ 
    int contains = Collections.indexOfSubList(mPlayed, mDespacito); 
    if (contains != -1){ 
     Log.d("Xylophone","You just played despacito"); 
     mPlayed.removeAll(mDespacito); 
    } 
} 

更多Collections.indexOfSubListhttps://www.tutorialspoint.com/java/util/collections_indexofsublist.htm

1

使用

mPlayed.equals(mDespacito); 

代替,这样的元素将在顺序和内容进行检查。

重要提示:如果您不使用字符串作为你的代码演示,你需要实现的hashCode并在您添加到列表中的类的equals。

下面的代码片段的结果显示真正两次,然后假

import java.util.ArrayList; 

public class MyClass { 
    public static void main(String args[]) { 
     ArrayList<String> a = new ArrayList(); 
     a.add("f"); 
     a.add("a"); 
     a.add("d"); 
     a.add("d"); 

     ArrayList<String> b = new ArrayList(); 
     b.add("f"); 
     b.add("a"); 
     b.add("d"); 
     b.add("d"); 

     System.out.println(a.equals(b)); 
     System.out.println(b.equals(a)); 
     b.add("c"); 
     System.out.println(a.equals(b)); 
    } 
} 

否则:您可以比较列表自己:

public boolean equals(List f, List s) { 
     if(f.size() != s.size()) 
     return false; 
     for(int i = 0; i < f.size(); i++) 
      if(!f.get(i).equals(s.get(i)) 
      return false; 
} 

但请记住,如果你不使用原语或字符串尖端你需要在你的对象上实现hashCode和equals。

+0

嗯,没有不行,太过。这次它甚至不显示你只玩过despacito。我认为这是因为mPlayed不等于mDespacito,它只是包含mDespacito –

+0

添加代码片段,看看它是否有效 –

0

list1.equals(list2)可用于

一个很不错的解释在下面的链接中给出。请找到。

https://stackoverflow.com/a/1075699/4994582

+0

嗯,没有不工作,也是。这次它甚至不显示你只玩过despacito。我认为这是因为mPlayed不等于mDespacito,它只包含mDespacito –