0

I am trying to define a method called add() that adds an object Fish to an array fish[]. How would I got about this without using arrayList? I keep receiving the error: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1

public class Pond {
private Fish[] fish;
private int numFish ;
private int capacity;

public Pond(int capacity){
    this.capacity = capacity;
}
public int getNumFish(){ return numFish;
}
public boolean isFull(){//Ponds can only have so many fish
    boolean Full = false;
    if (numFish >= capacity){
        Full = true;}
    return Full;
}
public void add(Fish aFish) {// puts a fish in the pond--OR-- replaces a fish that has been temporarily removed 
    if (numFish < capacity){
        fish[numFish++] = aFish;}
}
5
  • I keep receiving an error with the given code Commented Jan 31, 2014 at 23:45
  • 2
    What error are you getting? It looks like the fish array has not been initialised... Commented Jan 31, 2014 at 23:47
  • the error I receive is: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 Commented Jan 31, 2014 at 23:53
  • 1
    That error is because the array had not been initialised. Do it in the constructor and you'll be fine Commented Jan 31, 2014 at 23:54
  • @CarlDev an uninitialized array would mean throwing a NullPointerException. Commented Jan 31, 2014 at 23:59

2 Answers 2

1

Here dynamic array solution, which is a simple implementation of ArrayList method.

public void add(Fish aFish) {
    ensureCapacity();
    fish[numFish++] = aFish;
}

private void ensureCapacity() {
    if (numFish == fish.length) {
        int newSize = fish.length * 2;
        Fish[] newFish = new Fish[newSize];

        System.arraycopy(fish, 0, newFish, 0, fish.length);
        fish = newFish;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

In your constructor for pond you can add fish = new Fish[capacity] to set the initial size of the fish array to the capacity of your pond. Remember you can not add values to an array only change the values already there.

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.