Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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;
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading