2

I have three classes Main, Process and Employee. My problem is, the last object array always overwrites the first one. I don't think there is a problem with the logic, I simply use getters and setters.

    public class Main {

        public static void main(String args[]){
            Process p = new Process();

            p.setEmployeeList(p.generate());

            p.setExternalEmployeeList(p.generate());

            for(int i=0; i<5; i++){
                System.out.println(p.getEmployeeList()[i].getID());
            }

            System.out.println();

            for(int i=0; i<5; i++){
                System.out.println(p.getExternalEmployeeList()[i].getID());
            }

        }

    }

--

import java.util.Random;

public class Process {

    private int rndTemp;
    private int numberOfDice = 5;
    private Random random = new Random();
    public Employee[] employeeList = new Employee[5];
    public Employee[] externalEmployeeList = new Employee[5];
    private Employee[] tempList = new Employee[5];

    public Employee[] generate(){
        for(int i=0; i<numberOfDice; i++){
            rndTemp = random.nextInt((6 - 1) + 1) + 1;
            Employee emp = new Employee(rndTemp);

            tempList[i] = emp;
        }
        return tempList;

    }

    public Employee[] getEmployeeList(){
        return employeeList;

    }

    public Employee[] getExternalEmployeeList(){
        return externalEmployeeList;

    }

    public void setExternalEmployeeList(Employee[] externalEmployeeList){
        this.externalEmployeeList = externalEmployeeList;
    }

    public void setEmployeeList(Employee[] employeeList){
        this.employeeList = employeeList;
    }

}

--

public class Employee {

    public int empID;

    public Employee(int empID) {
        this.empID = empID;
    }


    public void setID(int empID) {
        this.empID = empID;
    }

    public int getID() {
        return empID;
    }
}
1
  • Which object arrays are you talking about? Commented Dec 19, 2014 at 8:05

2 Answers 2

5

You have to put

Employee[] tempList = new Employee[5];

inside your generate method and it will work as expected.

Otherwise you'll be passing only a reference to the array and next time you'll be overwriting the very same array.

Also, the other two arrays don't need to be initialized, since they will be assigned the newly created array.

Sign up to request clarification or add additional context in comments.

1 Comment

Also, use ArrayList or similar instead of old plain arrays, Java collection containers are quite optimized for speed and size and offer a lot of useful functions. docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
1

The problem is that tempList should be a local variable instead of a class variable.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.