-1

I am storing data in ArrayList. Now I want to split my ArrayList with sign "=". But while executing my code I am getting error. I want the data, which is written after equals to. Kindly check and help

My data in the arrayList is like that:

     SrNo=1
     DocCode=HRF03_V1_0
     CompCode=G&B
     EmpCode=11182
     fldMode=Apply For Leave
     fldLeaveType=CL
     fldFromDate=27/03/2015
     fldToDate=27/03/2015
     fldFullDays=1
     fldHalfDay=0
     fldWhichHalf=-
     fldReason=test
     fldTelExtn=
     fldLta=
     fldLtaSal=
     fldLtaYears=0
     fldNt=
     fldLtaAmt=
     fldLtaDays=
     fldEnc=
     fldEncDays=
     fldEncSal=
     fldEncAmt=
     fldPlAdv=

The Code:

String[] commaString =tableContent.toString().split(",");                
for(int i=0;i<commaString.length;i++){   
   strKey.add(commaString[i]);    
}
for (int i = 0; i <strKey.size(); i++) {
   System.out.println(strKey.get(i).toString().split("[1]);
}

error while executing my code:

java.lang.ArrayIndexOutOfBoundsException: 1
earthmover
  • 4,395
  • 10
  • 43
  • 74
  • Java has a `Properties` object for this – Reimeus Apr 13 '15 at 11:25
  • 1
    Are you sure you want to store it in a arraylist instead of Map? – The Coder Apr 13 '15 at 11:27
  • This is not a task for ArrayList. – JamesB Apr 13 '15 at 11:27
  • For samples like this `fldPlAdv=` there's no value on the right hand side, so after splitting your String[] will have only one element and [1] refers to second element which is not there, that's the reason you get ArrayIndexOutOfBoundsException – Arkantos Apr 13 '15 at 11:28
  • you really should go into properties file and acces them via ResourceBundle class like : `ResourceBundle settings = ResourceBundle.getBundle("settings");` then you can acces values like: `String empCode = settings.getString("EmpCode");` Modivy it at runtime? No problem: http://stackoverflow.com/questions/15337409/updating-property-value-in-properties-file-without-deleting-other-values – T.G Apr 13 '15 at 12:24

1 Answers1

1

Rows having nothing after = when splitted return an array containing only one element

e.g

fldEnc=
 fldEncDays=
 fldEncSal=
 fldEncAmt=

splitted by = return

["fldEnc"]
["fldEncDays"]
["fldEncSal"]
["fldEncAmt"]

So trying to access index 1 of those array will throw an ArrayIndexOutOfBoundsException

So to avoid your exception, try to replace

for (int i = 0; i <strKey.size(); i++) {
  System.out.println(strKey.get(i).toString().split("=")[1]);
}

by

for (int i = 0; i <strKey.size(); i++) {
  String[] splitted = strKey.get(i).toString().split("=");
  if(splitted.length > 1){
    System.out.println(splitted[1]);
  } else {
    System.out.println("No value for key:" + splitted[0];
  }
}
Vyncent
  • 1,185
  • 7
  • 17