0

While executing below code I'm getting:

(Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 3, Size: 3)

Please, suggest what could be the changes that I have to do.

import java.util.ArrayList;
import java.util.List;

public class Testing {

  public static void main(String[] args) throws Exception {
  // TODO Auto-generated method stub
  List < String > list1 = new ArrayList<String>();
  list1.add("A");
  list1.add("B");
  list1.add("C");
  List < String > list2 = new ArrayList<String>();
  list2.add("A");
  list2.add("D");
  list2.add("E");
  String str = null;
  String Strcom1;
  String Strcom2;
  int maxLength = list1.size();
  for (int i = 0; i <= list1.size(); i++) {
    for (int j = 0; j < list2.size(); j++) {
      Strcom1 = list1.get(i);
      Strcom2 = list2.get(j);
      //str=list1.get(1);
      //System.out.println(str);
      if (Strcom1.equals(Strcom2)) {
        System.out.println("Matching found");
      }
      else {
        System.out.println("No Matching found");
      }
    }
  }
  
}
Wyck
  • 10,311
  • 6
  • 39
  • 60
S.R.D
  • 201
  • 1
  • 3
  • 13

4 Answers4

1

You have to say '<' not '<=' in the first for-loop.

jherchen
  • 11
  • 1
0

The list 1 should be iterated from 0 to size-1, hence use this

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

instead of

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

0

replace this:

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

with:

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

reason: last position = list1.size()-1

0

You should be looping from 0 to list1.size()-1 since Lists are 0-indexed; your looping condition is therefore incorrect.

Change

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

To

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

You can also use a for each loop, as you only require the elements themselves, not the indexes.

for(String Strcom1 : list1){
    for(String Strcom2 : list2){
Unmitigated
  • 76,500
  • 11
  • 62
  • 80