简体   繁体   中英

arraylist indexoutofboundsexception index 0 size 0

Just wondering why I'm getting an indexoutofboundsexception after running whats basically a depth first search algorithm at matches.set(count,size)?

I get the error when I try to run it at position 0 in the arraylist, which seems weird at the default index is 0.

public void findInheritance(HashMap<String, ArrayList<String>> h, ArrayList<String> a) {

    Queue<String> search = new LinkedList();
    ArrayList<Integer> matches = new ArrayList<Integer>();
    int count = 0;
    String toBeSearched;
    int size = 0;

    for (String key: a) {
        size = 0;
        if (h.get(key).size() > 0 || h.get(key) == null) {
            search.addAll(h.get(key));
            while (search.size() > 0) {
                size++;
                toBeSearched = search.poll();
                if (h.get(toBeSearched).size() > 0) {
                    search.addAll(h.get(toBeSearched));
                }
            }
        }
        matches.set(count, size);
        count++;
    }

    int smallcount = 0;
    for (String b: a) {
        System.out.println(b);
        System.out.println(matches.get(smallcount));
        smallcount++;
    }
}
ArrayList<Integer> matches = new ArrayList<Integer>();
[...]
matches.set(count, size);

The list is empty, so there's nothing at index count , so it can't be replaced.

Also,

if (h.get(key).size()>0 || h.get(key) == null) {

This line is wrong: if h.get(key) can be null, then it will cause a NullPointerException. You should also call get() once and store the result in a variable.

Oh my word. I used .set instead of .add and the ArrayList was empty. My bad. Thanks for quick responses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM