简体   繁体   中英

How to add objects in an ArrayList multiple times

I add the details of a Person to an ArrayList twice, but when I want to print the two objects, it just repeats the final details twice (and it does not print the first).

import java.util.ArrayList;

public class Arraylist
{
    Person person = new Person();

    ArrayList<Person> array = new ArrayList<>();

    Person personTwo;
    Person personThree;
    void dataEntery(String name , int age , double marks, int itc, int pf)
    {
        person.addDetail(name,age,marks);
        person.marksDetail(itc,pf);

        array.add(person);
    }

    void print()
    {
        int index =0;
        while(index<array.size()) {
            personTwo = array.get(index);
            System.out.println(personTwo.name);
            System.out.println(personTwo.age);
            System.out.println(personTwo.marks);
            System.out.println(personTwo.itc);
            System.out.println(personTwo.pf);
            index++;
        }
    }
}

Can anyone explain why the first isn't printing and why the last prints twice?

You must create new Person instances or you simply add (and update) the same Person instance (because you only have one reference).

Person person = new Person(); // <-- something like this.
person.addDetail(name,age,marks);
person.marksDetail(itc,pf);

array.add(person);

I don't see where you are creating the person instance, but you have to create a new instance before each time you add a Person to the list. Otherwise, the list would contain the same instance multiple times.

The details you are seeing printed reflect the last udpates you made to that single instance, which are the details of the second Person .

void dataEntery(String name , int age , double marks, int itc, int pf)
{
    Person person = new Person();
    person.addDetail(name,age,marks);
    person.marksDetail(itc,pf);

    array.add(person);

}

Ok, so I figured out another way to do it. I feel really stupid about this, but I just now realized I could simply do this:

Fish bass = new Fish("bass", 5);

fishlist.add(bass);

for (Fish fish: fishlist) {
    if (fish.caught) {
        fishcaughtlist.add(new Fish(fish.name, fish.weight);
    }
}

So this will add a new instance that just takes all the info from bass. Thank you for helping tho :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM