Bravo
Bravo

Reputation: 1139

Getting OutOfBound exception

I am writing a java program which stores telephone directory information in an array. Whenever I am trying to put some entries inside this array, I get OutOfBound exception.

private int size = 0;
private Entry[] entryList = new Entry[size];

public ArrayDirectory(){

}

@Override
public void Add(String surName, String initials, int telNumber) {

    entryList[size] = new Entry(surName, initials, telNumber);
    size++;


}

    public static void main(String[] args){

    ArrayDirectory directory = new ArrayDirectory();

    directory.Add("Charles", "Johnson", 1234);

    System.out.println(directory.entryList.length);
}

Thank you for your attention

Upvotes: 0

Views: 119

Answers (3)

Harmlezz
Harmlezz

Reputation: 8068

An array can't be extends dynamically like an ArrayList. You initialized an array of size 0, which will never be able to hold any elements.

So, either use an ArrayList, which will increase in size dynamically, or initialize your array with the maximum amount of space you want / may spent.

Upvotes: 2

libik
libik

Reputation: 23029

At very beginning of your code, you have this

private int size = 0;
private Entry[] entryList = new Entry[size];

It means, you create array of size 0, therefore that array does not have any "cell", and accessing any values resulting in exception.

Upvotes: 0

Tom
Tom

Reputation: 16188

Arrays are fixed size. As soon as you create them with a set size that is the maximum number of elements they can hold.

private int size = 0;
private Entry[] entryList = new Entry[size];

You creating an array with size 0 which means no elements can be set in it.

private int size = 5;

Will allow you to put a maximum of 5 elements into it using indexes: 0,1,2,3,4

A better solution would be to use a dynamic array through an ArrayList. This will dynamically resize when more elements are added.

List<Entry> entryList = new ArrayList<Entry>();

entryList.add(new Entry());

Upvotes: 4

Related Questions