我正在为Android制作应用程序。我试图猜测用户刚刚在木琴上播放的是什么歌。我有:private List<String> mDespacito = new ArrayList<String>(Arrays.asList("f", "a","d","d"));
和private List<String> mPlayed = new ArrayList<String>();
当用户按下木琴上的一个键时,我将他按下的键添加到mPlayed arraylist中,如下所示:
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的所有元素(包括那些有两次的元素)以及它们是否按照正确的顺序排列。有没有我可以使用的命令?谢谢
答案 0 :(得分:1)
使用
{
"$schema": "http://json-schema.org/draft-06/schema#",
"title": "Product set",
"type": "array",
"items": {
"title": "Product",
"type": "object",
"properties": {
"id": {
"description": "The unique identifier for a product",
"type": "number"
},
"name": {
"type": "string"
},
"price": {
"type": "number",
"exclusiveMinimum": 0
},
"dimensions": {
"type": "object",
"properties": {
"length": {"type": "number"},
"width": {"type": "number"},
"height": {"type": "number"}
},
"required": ["length", "width", "height"]
},
"warehouseLocation": {
"description": "Coordinates of the warehouse with the product",
"$ref": "http://json-schema.org/geo"
}
},
"required": ["id", "name", "price"]
}
}
而是,因此将按顺序和元素检查元素。
重要提示:如果您没有使用Strings作为代码演示,则需要在添加到列表中的类中实现hashCode和equals。
以下代码段导致显示true两次,然后显示false
mPlayed.equals(mDespacito);
另外:您可以自己比较一下这个列表:
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));
}
}
但请记住,如果您不使用基元或String,则需要在对象上实现hashCode和equals。
答案 1 :(得分: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.indexOfSubList
的更多信息:
https://www.tutorialspoint.com/java/util/collections_indexofsublist.htm
答案 2 :(得分:0)