我正在使用数组列表来存储过去 5 周的时间戳列表。
i.e., if today is 2014-06-09, I want to store
2014-06-02
2014-05-26
2014-05-19
2014-05-12
2014-05-05
这是我的代码。
public class Test {
public static void main(String ap[]) throws InterruptedException{
List<Timestamp> ts = new ArrayList<Timestamp>();
Timestamp t = new Timestamp(new java.util.Date().getTime());
Timestamp temp = null;
for(int i=0;i<5;i++){
t.setTime(t.getTime()-(7*24 * (long)60* (long)60) * (long)1000);
temp = t;
System.out.println(t);
ts.add(temp);
temp = null;
}
}
}
但问题始终是我得到覆盖值的列表,即列表包含最后一个时间戳的所有元素,即 2014-05-05) 有人可以回答这个问题吗?
最佳答案
您没有获得"new"时间戳的原因是因为您不断覆盖相同的时间戳并将其添加到列表中 - 因此您最终会在列表中输入相同的对象 5 次,最后一个值将显示在“所有”项目。您不需要 temp
- 只需创建一个新的 Timestamp
对象并将其添加到列表中即可:
List<Timestamp> ts = new ArrayList<Timestamp>();
Timestamp t = new Timestamp(new java.util.Date().getTime());
for(int i=0;i<5;i++){
t.setTime(t.getTime()-(7*24 * (long)60* (long)60) * (long)1000);
System.out.println(t);
ts.add(new Timestamp(t.getTime()));
}
关于java - 时间戳列表覆盖前一个时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24115560/