My Will
My Will

Reputation: 410

Why does ArrayList return error: ArrayIndexOutOfBoundsException

I don't know why it is. I read my text file line by line, cut the line by split and save them to an ArrayList. But my program can't work if the file longer than 100 lines,so it returns an error at split command. I wonder if my computer is out of memory?

Everybody, who can make it obvious? thank you in advanced. Here is my code:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.JOptionPane;
class Vocab implements Comparable<Vocab>{
    private String vocab;
    private String explanation;
    public Vocab(String vocab, String explanation) {
        this.vocab = vocab;
        this.explanation = explanation;
    }
    public int compareTo(Vocab that){
        return this.vocab.compareTo(that.vocab);
    }    
    public String getVocab() {
        return vocab;
    }
    public void setVocab(String vocab) {
        this.vocab = vocab;
    }
    public String getExplanation() {
        return explanation;
    }
    public void setExplanation(String explanation) {
        this.explanation = explanation;
    }
}
public class Test {
    public static void readFile(String fileName, ArrayList<String> a) throws FileNotFoundException {
        try {
            File fileDir = new File(fileName);
            BufferedReader in = new BufferedReader(
                new InputStreamReader(
                    new FileInputStream(fileDir), "UTF8"));
        String str;
        while((str= in.readLine())!= null){
               a.add(str);                 
        }
        in.close();
        }         
        catch (IOException e) 
        {
            JOptionPane.showMessageDialog(null,"Something in database went wrong");
        }                    
    }        
    public static void main(String[] args) throws FileNotFoundException {
        // TODO code application logic here
        ArrayList<Vocab> a= new ArrayList<Vocab>();
        ArrayList<String> b= new ArrayList<String>();
        readFile("DictVE.dic",b);
        for (String t: b){
            String[] temp= t.split(":");
            a.add(new Vocab(temp[0].trim(), temp[1].trim()));// error in here
        }
    }    
}

and here is my file: DictEV.dic

Upvotes: 1

Views: 70

Answers (1)

Andy Turner
Andy Turner

Reputation: 140318

There is a subtle gotcha in the String.split(String) method, which is that empty tokens are discarded from the end of the string:

Trailing empty strings are therefore not included in the resulting array.

So:

System.out.println("Hello:".split(":").length); // Prints 1.

You can keep the empty strings by passing a negative int as a second argument:

System.out.println("Hello:".split(":", -1).length); // Prints 2.

Upvotes: 4

Related Questions