-2
public class TEST {
    
    public static void main(String[] args) {
         String role1=null,role2=null,role3=null,role4=null,role5=null;
         String role1Alloc=null,role2Alloc=null,role3Alloc=null,role4Alloc=null,role5Alloc=null;
                
         LinkedHashMap<String, Integer> lhm = new LinkedHashMap<>();
         lhm.put("a", 6);
         lhm.put("b", 4);
         lhm.put("c", 7);
                
         String[] Keys = new String[lhm.size()];
         Integer[] Values = new Integer[lhm.size()];
         int i = 0;
         for (Map.Entry mapElement : lhm.entrySet()) {
             String key = (String) mapElement.getKey();
             int value = ((int) mapElement.getValue());
             Keys[i] = key;
             Values[i] = value;
             i++;
         }
                
         role4=Keys[4];// java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 3
         // but  i want set role4 as null if element is not present in array
    role4Alloc=Values[4];//java.lang.ArrayIndexOutOfBoundsException: Index 4 out of bounds forlength 3
         // but  i want set role4Alloc  as null if element is not present in array  
                
         }
     }
}
akarnokd
  • 69,132
  • 14
  • 157
  • 192
  • A simple check with an `if` statement would do the trick... `if (Keys.length > 4) role4Alloc=Keys[4]; else role4Alloc = null;` – sorifiend Jun 22 '22 at 06:14
  • Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – QBrute Jun 22 '22 at 08:17

1 Answers1

1

There are only 3 elements in the LinkedHashMap and so when you initialized the array with lhm.size() it will initialize the Array with size 3 and so if you try to access 4th index in the array you will obviously get ArrayIndexOutOfBoundsException

Shridutt Kothari
  • 7,326
  • 3
  • 41
  • 61