Swa*_*esh 8 java arrays string collections
我有一个List声明:
List<String[]> arrayList = new ArrayList<>();
Run Code Online (Sandbox Code Playgroud)
这List包含多个Strings 数组.
我需要检查一下String[]我所拥有的是否包含在内ArrayList<String[]>.
我目前正在迭代ArrayList并将每个String[]与我正在搜索的那个进行比较:
for(String[] array: arrayList){
if(Arrays.equals(array, myStringArray)){
return true;
}
}
return false;
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来检查是否ArrayList<String[]>包含特定的String[]?
Array.equals()是最有效的方法AFAIK.该方法仅用于此目的并且在当前的实施状态(即单个for循环)中进行优化.
只是去吧.
我同意Rod_Algonquin的答案,但还有另一种方法可以做到.只需编写自己的包装数组的类并实现自定义的equals和hashCode方法,并让它们返回Arrays.equals()和Arrays.hashCode().使用此方法,您可以将对象存储在List中,并直接对列表进行检查.
List<ArrayWrapper> list = new ArrayList<ArrayWrapper>();
list.add(new ArrayWrapper(new String[]{"test", "123"}));
list.add(new ArrayWrapper(new String[]{"abc", "def"}));
list.add(new ArrayWrapper(new String[]{"789", "cgf"}));
String[] arrayToSearchFor = {"test", "123"};
ArrayWrapper wrapperToSearchFor = new ArrayWrapper(arrayToSearchFor);
System.out.println(list.contains(wrapperToSearchFor));
String[] arrayToSearchFor2 = {"hello", "123"};
ArrayWrapper wrapperToSearchFor2 = new ArrayWrapper(arrayToSearchFor2);
System.out.println(list.contains(wrapperToSearchFor2));
class ArrayWrapper
{
private String[] array;
public ArrayWrapper(String[] array)
{
this.array = array;
}
public String[] getArray()
{
return array;
}
@Override
public int hashCode()
{
return Arrays.hashCode(array);
}
@Override
public boolean equals(Object obj)
{
if (!(obj instanceof ArrayWrapper))
{
return false;
}
return Arrays.equals(array, ((ArrayWrapper) obj).getArray());
}
}
Run Code Online (Sandbox Code Playgroud)
这将打印
true
false
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7056 次 |
| 最近记录: |