Sebastian Sebastian - 1 month ago 15
Java Question

Custom List duplicates last added element

I have made a custom list and added two elements to my list.
when I try to display these two elements, It only displays the last added element twice. I am a beginner in java, I cant seems to find why my list only contains last added item in duplicate !

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Home {

public static void main(String[] args) {
int length = 2;
String[] machineName = { "BMW", "AUDI" };

for (int i=0; i<length; i++){
setMachineDetails(machineName[i]);
System.out.println("Machine Details No. : " + i + " SET");
}

System.out.println("\n\nDisplaying List contents\n\n");

System.out.println("Size of List : " + MachineDetails_List.serverData.size() + "\n\n");

for (MachineDetails model : MachineDetails_List.serverData){
System.out.println("MachineDetails Name : " + model.getMachineName());
}
}

private static void setMachineDetails(String name) {

MachineDetails md = new MachineDetails();
md.setMachineName(name);
MachineDetails_List.serverData.add(md);
System.out.println("Machine Name : " + name + " SET");
}
}

class MachineDetails {
public static String MACHINE_NAME;

public static String getMachineName() {
return MACHINE_NAME;
}

public static void setMachineName(String machineName) {
MACHINE_NAME = machineName;
}
}

class MachineDetails_List {

public static List<MachineDetails> serverData = new ArrayList<MachineDetails>();

public static List<MachineDetails> getServerData() {
return serverData;
}

public static void setServerData(List<MachineDetails> serverData) {
MachineDetails_List.serverData = serverData;
}
}

Answer

The MACHINE_NAME don't need to be static. Since the field is static, all of the MachineDetails object's MACHINE_NAME will have same value.

Remove static keywords from MachineDetails class:

class MachineDetails {

    public String MACHINE_NAME;

    public String getMachineName() {
        return MACHINE_NAME;
    }

    public void setMachineName(String machineName) {
        MACHINE_NAME = machineName;
    }
}