Skip to content
Advertisement

How to update a single array using multiple instances of a class

How can I make two instances of a class, update the same array from that class? Like here, I want r1 and r2 to update same pendingOrders, so that finally the array is [‘yo’, ‘lo’]. That is not happening, the r1 and r2 are making different arrays.

import java.util.ArrayList;

public class Student{

    static int enrollmentNumber;
    String studentName;

    Student(String name){
        enrollmentNumber += 1;
        studentName = name;
    }

    public String toString(){
        return enrollmentNumber+": "+this.studentName;
    }

    public static void main(String[] args) {

        Student s = new Student("Pam");
        System.out.println(s.toString());
        
        Student s1 = new Student("Hellooo");
        System.out.println(s1.toString());


        Student s2 = new Student("Pam2");
        System.out.println(s2.toString());
        
        
        Robot r1 = new Robot("Bob");
        r1.addToQueue("yo");
        System.out.println(r1.returnList()); // prints: ['yo']
        
        Robot r2 = new Robot("Rob");
        r2.addToQueue("lo");
        System.out.println(r2.returnList()); // prints: ['lo']
        // But I want it to print ['yo', 'lo']

    }
}

class Robot{
    public ArrayList<String> pendingOrders = new ArrayList<String>();
    String rName;

    Robot(String name){
      rName = name;
    }

    public void addToQueue(String s){
        pendingOrders.add(s);
    }
    
    public ArrayList returnList(){
        return pendingOrders;
    }
}

Advertisement

Answer

Add the static keyword to the pendingOrders in Robot.
Check this guide for more info

Advertisement