【发布时间】:2011-01-27 17:21:52
【问题描述】:
我正在向 ArrayList 添加元素,它会正确添加第一个元素,但是当我添加任何后续元素时,它会用最近添加的值替换其他元素,并向 ArrayList 添加一个新元素。
我使用 arraylist 和 ints 甚至另一个创建的类进行了测试,它运行良好,但是我在这里使用的自定义类会导致问题。
数组列表的代码是
public static void main(String args[]){
List<BasicEvent> list = new ArrayList<BasicEvent>();
list.add(new BasicEvent("Basic", "Door", 9, 4444, new Date(12,04,2010), new Time(12,04,21), 1, 0.98, 0));
list.add(new BasicEvent("Composite", "Door", 125, 4444, new Date(12,04,2010), new Time(12,04,20), 1, 0.98, 1));
list.add(new BasicEvent("Basic", "Door", 105, 88, new Date(12,04,2010), new Time(12,05,23), 1, 0.98, 0));
list.add(new BasicEvent("Basic", "Door", 125, 12, new Date(12,04,2010), new Time(12,05,28), 1, 0.98, 1));
list.add(new BasicEvent("Basic", "Door", 129, 25, new Date(12,04,2010), new Time(12,05,30), 1, 0.98, 0));
list.add(new BasicEvent("Basic", "Door", 125, 63, new Date(12,04,2010), new Time(12,04,20), 1, 0.98, 1));
list.add(new BasicEvent("Basic", "Detect", 127, 9, new Date(12,04,2010), new Time(12,05,29), 1, 0.98, -1));
for(int i=0;i<list.size();i++) {System.out.println("list a poition " + i + " is " + BasicEvent.basicToString(list.get(i)));}
而自定义类basicEvent的代码是
public class BasicEvent {
public static String Level;
public static String EType;
public static double xPos;
public static double yPos;
public static Date date;
public static Time time;
public static double Rlb;
public static double Sig;
public static int Reserved;
public BasicEvent(String L, String E, double X, double Y, Date D, Time T, double R, double S, int Res){
Level = L;
EType = E;
xPos = X;
yPos = Y;
date = D;
time = T;
Rlb = R;
Sig = S;
Reserved = Res;
};
public static String basicToString(BasicEvent bse){
String out = bse.getLevel() + ";" + bse.getEtype() + ";" + bse.getxPos() + ";" + bse.getyPos() + ";" + bse.getDate().dateAsString() + ";" + bse.getTime().timeAsString() + ";" + bse.getRlb() + ";" + bse.getSig() + ";" + bse.getReserved();
return out;
}
【问题讨论】:
-
尝试重新格式化 BasicEvent 的代码,使其看起来像问题中的实际代码,谢谢。
-
你得到了什么输出,你期望什么?
-
为什么你的班级成员是静态的?
-
new Date(12,04,2010)至少有 2 个错误,可能是 3 个。2010并不表示您认为在这种情况下发生的年份,04是八进制二进制,只要您到达08你会注意到问题,04(以及4)可能并不表示你认为的月份,请检查该构造函数的 Javadoc。