我有两个不同大小的字符串arraylists。我需要比较这两个arraylists并获取输出。但它的错误为"Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 6, Size: 6"
。我需要对此错误进行哪些更改。我的代码是,
import java.util.ArrayList;
import java.util.Arrays;
public class TestCompareArrays {
public static void main(String[] args) {
ArrayList<String> arr1 = new ArrayList<String>(Arrays.asList("a","b","c","d","e","f"));
ArrayList<String> arr2= new ArrayList<String>(Arrays.asList("b","d","f"));
for(int i = 0; i <= arr1.size(); i++){
if(arr2.contains(arr1.get(i))){
System.out.println("yes");
}
else{
System.out.println("No");
}}
}}
答案 0 :(得分:2)
尝试替换它:
for(int i = 0; i <= arr1.size(); i++){
使用<
代替<=
,如下所示:
for(int i = 0; i < arr1.size(); i++){
因为ArrayList的大小从0
开始到size()-1
。
答案 1 :(得分:0)
使用retain all
,快速准确,高效:
String orig[] = { "a", "b", "b", "c" };
String act[] = { "x", "b", "b", "y" };
List origList = new ArrayList(Arrays.asList(orig));
List actList = Arrays.asList(act);
origList.retainAll(actList);
System.out.println(origList);