2
public class ReadToHashmap {
public static void main(String[] args) throws Exception {
    Map<String, String> map = new HashMap<String, String>();
    BufferedReader in = new BufferedReader(new FileReader("example.tab"));
    String line = "";
    while ((line = in.readLine()) != null) {
        String parts[] = line.split("\t");
        map.put(parts[0], parts[1]);
    }
    in.close();
    System.out.println(map.toString());
 }
}

while inserting the key with value in HashMapI am getting ArrayIndexOutOfBoundException exception on:-

map.put(parts[0], parts[1]);
2
  • 2
    You don't seem to be checking the number of elements in the parts array before assuming it has at least two elements. Commented Oct 13, 2015 at 3:23
  • The question title is misleading as ArrayIndexOutOfBoundException isn't thrown by any method of HashMap but by the String array parts[] whose length in some case is less than 2. Commented Oct 13, 2015 at 4:47

3 Answers 3

3
String parts[] = line.split("\t");

Because you are expecting that each of the input String will be separated by tab space. But that is not happening for at least one input. Please check the input. That is why you are getting an exception here.

map.put(parts[0], parts[1]);

To debug this, you can print the content (line) and length (parts.length) to System.out just before putting them into the HashMap.

Sign up to request clarification or add additional context in comments.

2 Comments

actually i have a file in which after running through a algorithm it gives me output in 2 columns but data in columns vary. for examle:-- first line 12 1212 second line 1213123 213321. there are two spaces in between
Can you provide some sample of how the columns vary?
0

Maybe you could replace

map.put(parts[0], parts[1]);

with

if(parts!=null && parts.length>=2)  
   map.put(parts[0], parts[1]);

Comments

0

You are trying to split the line with tab, and for sure they are not being splited thats why it is giving you ArrayIndexOutOfBoundException in HashMap.

if you are using any IDE then debug it.

and Make sure TAB is equal to 4-spaces not 2-spaces as you mentioned, this is the reason why it is not splited.

Update

Apart from your problem , always use null checks and size checks before using the arrays of collections if you are getting it from some logic as you need min length of 2.

 while ((line = in.readLine()) != null) {
        String parts[] = line.split("\t");
        map.put(parts[0], parts[1]);
    }

rather use

while ((line = in.readLine()) != null) {
        String parts[] = line.split("\t");
        if(parts!=null && parts.length>=2){
            map.put(parts[0], parts[1]);
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.