Win a copy of Java Mock Exams (software) this week in the Programmer Certification (OCPJP) forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Everytime an object is added to the arraylist it replaces the last instead of adding to the list

 
davey smithy
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Im trying to create a student class and course class which contains an arraylist of students, and everytime a new student is added to the arraylist it should increase the number of students but it is replacing the previous student. How would I make it so it doesn't replace it?

The code for the main class is:


The code for Student class is:


The code for the course class:
 
Vaishakh Menon
Greenhorn
Posts: 18
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you creating a new ArrayList each time  you create an Object ?
If not then why are you creating an ArrayList inside the constructor Of Course Class

I Think you should create the ArrayList outside the constructors and it will work fine...
 
Henry Wong
author
Sheriff
Posts: 22613
111
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

There is only one method that actually adds a Student instance to an array list ... but ... nowhere in your code, do you call that method. So, your arraylist should be empty.

Henry
 
Vaishakh Menon
Greenhorn
Posts: 18
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Henry I think its not replacing the last Object in the ArrayList ,it is creating  a new arrayList whenever he creates an object.
Hence there is always only one Object in the Arraylist ie the last added Object.

Please correct me if I am Wrong.
 
Dave Tolls
Ranch Hand
Posts: 2369
25
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As Henry says.
There's nowhere that any Students are added to the ArrayList.

However, if we look at how the course and student details are printed out, you can see that only the last Student is printed...which is where the I am guessing davey is seeing it as only the last Student is printed.

Which leads to the post I made in the other thread.

It is now clearer what you are trying to achieve.

First off you need to add each Student to the course.
Next you need to make sure the Student you create is inside the loop, since it isn't needed outside the loop.
Outside the loop you can then print the Course, which should include iterating over the Students in that Course and printing them out one at a time.
 
Happiness is not a goal ... it's a by-product of a life well lived - Eleanor Roosevelt. Tiny ad:
the new thread boost feature: great for the advertiser and smooth for the coderanch user
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!