如果您希望将一个数组的元素复制到另一个数组,您需要做的第一件事是遍历一个数组的元素,如果找到匹配项,则将其存储到另一个数组中。
假设你有以下数组:
String[] arr = new String[]{"S1!!T1", "S1!!T2", "S1!!T3", "S2!!T1", "S2!!T2", "S3!!T1", "S3!!T2", "S3!!T3"};
在遍历数组之前,我们不知道数组中有多少元素会匹配,所以我们有两个选择:
- 创建另一个与 arr 大小相同的数组(如果不是所有的 arr 条目都重新匹配,则会导致数组中出现一些空值)
- 使用 ArrayList,然后根据需要将 ArrayList 转换为数组
见下文:
public static void main(String[] args) {
String[] arr = new String[]{"S1!!T1", "S1!!T2", "S1!!T3", "S2!!T1", "S2!!T2", "S3!!T1", "S3!!T2", "S3!!T3"};
List<String> s2List = new ArrayList<String>();
//loop through arr and for each element check if it contains S2
for(int i = 0; i < arr.length; i++) {
//if it contains S2 then it returns true and we add it to list
if(arr[i].contains("S2")) {
//add to list the element
s2List.add(arr[i]);
}
}
//print the list for testing
System.out.println(s2List);
//if you wish to store the elements to array then
//now we know how many matched, so we can create array with the
//size of elements in s2List
String[] sArr = new String[s2List.size()];
//Here loop through the list and assign values to array
for(int i = 0; i < s2List.size() ; i++) {
sArr[i] = s2List.get(i);
}
//print the array
System.out.println(Arrays.toString(sArr));
}
您也可以使用其他方法将列表直接转换为数组,但是,以上应该让您了解如何解决您提出的问题。