Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

arrayList object detail retrieval

807591May 21 2008 — edited May 21 2008
Hi All

I have to create an arrayList of objects. I don't know how many I will require until necessary. I would like to create the list with individual object names for explicit referencing. I was unable to do this and so have created an arrayList of objects where each object has the same name however, they are stored individually and so I should be able to reference them individually via the arrayLists index. This is just as good.

The problem I have is, as I add each object, I set it's title using the iterator.

My test output is good to this point, it shows that each object is assigned it's title correctly and the arrayList expands correctly.

When I retrieve each object form the arrayList, and check it's title, it only shows the title as the final iterator value form the previous function.

Here is the relevant code:
/** Variable declarartion */
Ball ball = new Ball();

int newBallPool = 45;

ArrayList<Object> ballTitles = new ArrayList<Object>();

int title;

/** Create the objects */
    public void createBalls(int newBallPool){

        for(int i = 1;i<newBallPool+1;i++){

            ball.setBallTitle(i);

            System.out.println("Title set is: "+ball.getBallTitle());

            ballTitles.add(ball);

            System.out.println("Current arrayList size is: "+ballTitles.size());

        }

    }


/** Retrieve the objects and check their titles */
    public void checkDetails(){

    System.out.println("Size of arrayList is: "+ballTitles.size());

        int checker;

        for(int i = 0;i<ballTitles.size();i++){

            checker = i + 1;

            Ball currentBall = (Ball) ballTitles.get(i);

            System.out.println("Title of ball "+checker+" is: "+currentBall.getBallTitle());

        }

    }
The Ball class methods are as follows:
/** Set title */
 public void setBallTitle(int newBallTitle){

        ballTitle = newBallTitle;

    }

/** Get title */
    public int getBallTitle(){

        return ballTitle;

    }
I realise the above may not be the most appropriate or most efficient use of code however this is early learning for me!

I hope someone can see where I am going wrong. Thanks.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 18 2008
Added on May 21 2008
8 comments
100 views