自定义列表重复上次添加的元素

时间:2016-10-10 07:34:23

标签: java

我制作了一个自定义列表,并在我的列表中添加了两个元素。 当我尝试显示这两个元素时,它只显示最后添加的元素两次。我是java的初学者,我似乎无法找到为什么我的列表只包含最后添加的项目一式两份!

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

2 个答案:

答案 0 :(得分:2)

MACHINE_NAME不一定是static。由于该字段是静态的,因此MachineDetails个对象MACHINE_NAME的所有内容都具有相同的值。

static类中删除MachineDetails个关键字:

class MachineDetails {

    public String MACHINE_NAME;

    public String getMachineName() {
        return MACHINE_NAME;
    }

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

答案 1 :(得分:0)

You should make list,variable to be non static.

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

class MachineDetails {

    public String MACHINE_NAME;

    public String getMachineName() {
        return MACHINE_NAME;
    }

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