Skip to content

Thrown 【IndexOutOfBoundsException】 when running the A_Star algorithm #2826

@renjiancheng

Description

@renjiancheng

Describe the bug

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
	at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
	at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
	at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:266)
	at java.base/java.util.Objects.checkIndex(Objects.java:359)
	at java.base/java.util.ArrayList.set(ArrayList.java:441)
	at com.thealgorithms.datastructures.graphs.A_Star$Graph.<init>(A_Star.java:20)
	at com.thealgorithms.datastructures.graphs.A_Star.main(A_Star.java:134)

code

    public E set(int index, E element) {
        Objects.checkIndex(index, size); 
        E oldValue = elementData(index);
        elementData[index] = element;
        return oldValue;
    }

The size and index are both 0 when initialized,It is recommended to call the add method instead of set

fixed

        public Graph(int size) {
            this.graph = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                this.graph.add(new ArrayList<>());
            }
        }

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions