2016-02-21 101 views
0

我有兩個不同大小的字符串arraylist。我需要比較這兩個數組列表並輸出。但它給出了一個錯誤"Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 6, Size: 6"。我需要爲這個錯誤做些什麼改變。我的代碼,在Java中比較兩個不同大小的字符串arraylist

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"); 
        }} 
}} 
+1

'對(INT I = 0; I

回答

1

嘗試更換此:

for(int i = 0; i <= arr1.size(); i++){ 

隨着使用<代替<=這樣的:

for(int i = 0; i < arr1.size(); i++){ 

因爲ArrayList的大小開始從0size()-1

0

使用retain all,IST快速精確和有效的:

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);