我制作了一个自定义列表,并在我的列表中添加了两个元素。 当我尝试显示这两个元素时,它只显示最后添加的元素两次。我是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;
}
}
答案 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;
}
}