ArrayList is being overwritten

why does adding a new value to list overwrite previous values in the list
arraylist add overwrites with last value
java append arraylist
adding objects to arraylist java
java update arraylist object
override add method arraylist java
add items to arraylist java
arraylist replace

I am trying to add a new train to my arraylist but upon adding the train, the existing content of the arraylist gets overwritten by the new input. This results in having only one item in the arraylist without being able to add more without overwriting the other. As I do not quite know what the source of this problem in the code is, I came looking for help here.

Within this class the train is being made:

public class RCommand extends RBaseListener {
        Company mycompany = new Company("traincompany");

        public void enterNewtraincommand(RParser.NewtraincommandContext ctx) {
            System.out.println("Now creating new train " + ctx.getText());
            mycompany.addTrainTo(new Train(ctx.getChild(2).toString()));

In this class the train is supposed to be added to the list.

public class Company{

        private String name;
        List<Train>trains = new ArrayList<Train>();

        public void addTrainTo(Train train) {
                for (Train t :trains) {

Simply test for your class Company to see if if work

    public class Test {
        Company company = new Company();

        public static void main(String[] args) {
            Test test = new Test();

    private void start() {

    System.out.println("IT work");
    company.addTrainTo(new Train("One"));
    System.out.println("End first add");
    company.addTrainTo(new Train("two"));
    System.out.println("End second add\n");

    System.out.println("Follow example will not work");
    company = new Company();
    company.addTrainTo(new Train("One"));
    System.out.println("End first add");
    company = new Company(); // <--- create the ERROR
    company.addTrainTo(new Train("two"));
    System.out.println("End second add");

Suppose we have train as is:

public class Train {
    private String name;

    public Train(String name) { = "Train" + name;

    public String getName() {
        return name;

Output is:

IT work

Train One

End first add

Train One

Train two

End second add (it work fine)

Follow example will not work

Train One

End first add

Train two

End second add<- we miss the first train because we recreate the company instance

So it work.

So the error is not in this class Company.

  1. Check if the caller of Company recreate the class Company before adding new train
  2. Check class train if it has something strange (static attribute for name or similar)

ArrayList add method overwriting elements? : javahelp, Unfortunately the ArrayList is being overwritten. Here is the Customer class: public class Customer { private static String customer; private static double amount;  I am trying to add Node objects to the arraylist children but it appears that when the second object is added to the arraylist the first node object is being overwritten could someone please assist me with correcting this issue.

Looks like new "trains" object is being created for each addition. After adding, try to print the address of "trains" object to find out for sure. You can print the address by System.out.println("trains address is: " + trains)

Topic: Why the all the arraylist values are overwritten, I have a problem with arraylist, that is the added items are being overwritten with the newly added item. check the code below. $Finalresult=@() Dear All, I am very new to, I used ArrayList in a project and I observed that arraylist overwrites the previous items in the arraylist. <serializable()> _ Public Class benchPortalPara Public name As String = "" Public attribute As String = "" Public time As Double = 0.0 Public CmdCnt As Integer = 0 'ToDo: to remove <(XmlArrayItem(Type:=GetType(benchPortalPara)), _ 'XmlArrayItem(Type

You did't pass for us all your code required but I think, you should create a Company constructor with your train List.

Something like that:

public class Company{

        private String name;

        public Company(String name, List<Train> trains){
   = name;
            this.trains = trains;


Then in your RCommand class use your new Constructor

    Company mycompany = new Company(new ArrayList<Train> ,"traincompany");

And it will be fine. Your mistake in code is creating new trains list every time by calling new operator.

How to add a an object to a arraylist without overwriting other , However the objects in the arraylist are being overwritten by the last object added​. How do I stop from overwriting all the objects in the list ?? I guess I'm a little lost because you're asking about an ArrayList, but I don't see an ArrayList. What you have is an application-level variable (Application["imie_a"]) that gets updated when you add the contents of the TextBox when the Button is clicked.

Objects of ArrayList Overwriting, I'm having trouble getting new objects to add to an ArrayList. Intead, everytime a new object is created and added, it overwrites the first object. So. Is this where the issue is being caused? Did I initialize the variables  ArrayList Being overwritten. (json) Dim StartTimeValueArray As New ArrayList Dim EndTimeValueArray As New ArrayList Util.JsonHelper._keyToSearch = "StartTime

ArrayList overwriting values when add elements - MSDN, Every time I add an element to my ArrayList it, it adds the element but also overwrites the values added previously. Here's my code: The object will then be placed into a a arraylist; I Run the program and it creates the correct number of Entity objects in the arraylist. The objects are created and the correct information is being placed inside them. However the objects in the arraylist are being overwritten by the last object added.

2d array within a arraylist of objects being overwritten after the new , Hello All, I am currently having a problem in creating an arraylist of objects, each with store a group of various data to be used to draw different  So I am attempting to use ArrayLists to store a list of Customers. A customer is an object that has a String name and double amount (sale). I am allowing the user to input more than one customer name and their sale amount and then add these customers to an ArrayList. Unfortunately the ArrayList is being overwritten. Here is the Customer class:

  • You should initialize the list of trains in Company's constructor.
  • I tried that, but I didn't seem to work. I might have done it wrong though. Could you give me an example?
  • Are you sure that RCommand is not recreated every time you call enterNewtraincommand?
  • trein Is that a typo?
  • @hashmap initializing a member inline is like implicitly initializing it in all the consturtors.
  • Please explain why down vote? The test demonstrate that class company work fine...
  • I do not know who downvoted, but thanks to your code above, I was able track the problem within the code. You see, everytime I gave the command of adding a new train, the code in the class RCommand was being runned. This resulted in the creation of multiple companies. So I went back to the class that RCommand extends and the class that that class extends (confusing IK) and pasted 'Company mycompany = new Company("traincompany");' there. And now it seems to work. I was able to find this thanks to you!
  • Thank you so much for your feedback :) happy to help someone!
  • Chris If this response is fine please give me a point clicking on the up arrow :)!