0

I have the next problem to compile using NetBeans and console in Ubuntu 14.04:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

My code is (in the line of error):

Object maxFreK = map.keySet().toArray()[0];

How can I solve it?

Thanks!

WhiteShadow
  • 103
  • 2
  • 10

2 Answers2

0

java.lang.ArrayIndexOutOfBoundsException : 0 means that your array doesn't contain any elements.
It is an empty array.

You can use somenthing like this:

Object maxFreK=null; 
if (!map.isEmpty()){
  maxFreK = map.keySet().toArray()[0];
}
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
0

This exception shows that your map is empty and your are accessing the first key which is not present. Before accessing any element from the keyset, check if the array/keyset contains elements

for e.g.

Object [] objArr = map.keySet().toArray();
if(objArr.length>0){
   Object maxFreK = objArr [0];
}
Vivek Singh
  • 2,047
  • 11
  • 24