让我说我的ArrayList是:
["b1, "b2", "b3"]
我的多维数组是:
[["b", "b2", "b3"], ["b4", "b5", "b6"], ["b7", "b8", "b9"], ["b", "b4", "b7"], ["b2", "b5", "b8"], ["b3", "b6", "b9"], ["b", "b5", "b9"], ["b3", "b5", "b7"]];
我想检查我的ArrayList中的所有三个值是否也在我的多维数组中。
答案 0 :(得分:0)
手头的问题是订单无关紧要。为了避免进一步的复杂化,您可以简单地“排序”给定数组中的每一行(让我们的名字为wordsArray2D
),以及您的列表(让我们称之为wordsList
)。以下是一个示例实现:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String... args) {
// This is our "dictionary" of given "lines".
String[][] wordsArray2D = {{"b1", "b2", "b3"},
{"b4", "b5", "b6"},
{"b7", "b8", "b9"},
{"b", "b4", "b7"},
{"b2", "b5", "b8"},
{"b3", "b6", "b9"},
{"b", "b5", "b9"},
{"b3", "b5", "b7"}};
// To neglect order, sort each line (since String is Comparable,
// let's do Array.sort(...) the work for us)
for (int idx = 0; idx < wordsArray2D.length; ++idx) {
Arrays.sort(wordsArray2D[idx]);
}
// Our input, as List<String>. Add some content
List<String> wordsList = new ArrayList<String>();
wordsList.add("b2");
wordsList.add("b1");
wordsList.add("b3");
// To start form even ground, convert the List into an Object[]...
Object[] wordsListAsArray = wordsList.toArray();
// ... and sort it as well. Again - this gets rid of ordering problems.
Arrays.sort(wordsListAsArray);
for (String[] wordsArray : wordsArray2D) {
// Tow String[] are equal, iff their Strings at the correspinding
// indices are equal. For this, we can use Arrays.equals(...)
if (Arrays.equals(wordsArray, wordsListAsArray)) {
System.out.println("found.");
break;
}
}
}
}
答案 1 :(得分:0)
使用Collections.sort(Some collection)
对多维数组中的每个列表进行排序。稍后使用equals()
ArrayList all=new ArrayList();
ArrayList<String> al=new ArrayList<String>();
al.add("a");
al.add("b");
al.add("c");
ArrayList<String> al1=new ArrayList<String>();
al1.add("c");
al1.add("b");
al1.add("a");
ArrayList<String> al2=new ArrayList<String>();
al2.add("a");
al2.add("c");
al2.add("b");
ArrayList<String> al3=new ArrayList<String>();
al3.add("a");
al3.add("b");
al3.add("c");
all.add(al1);all.add(al2);all.add(al3);
for(int i=0;i<all.size();i++)
{
ArrayList tmp=(ArrayList)all.get(i);
Collections.sort(tmp);
if(tmp.equals(al))
System.out.println(all.get(i));
//if both are same then do some action here.
}
<强>输出:强>
[a, b, c]
[a, b, c]
[a, b, c]