Java 有没有办法在不使用引用的情况下将日期对象复制到另一个日期对象中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28332484/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to copy Date object into another date Object without using a reference?
提问by Ted pottel
I got a program that loads in raw data for charting and stores it in a class called cRawGraph
.. It then formats this data and stores it in another class called cFormatGraph
. Is there a way to copy some of the date objects stored in cRwGraph
to date objects stored in cFormattedGraph
without using a reference? I looked at Oracle's documentation and did not see a constructor that would take in a date object or any methods data would accomplish this.
我得到了一个程序,它加载原始数据用于图表并将其存储在一个名为cRawGraph
..的类中。然后它格式化这些数据并将其存储在另一个名为cFormatGraph
. 有没有办法cRwGraph
在cFormattedGraph
不使用引用的情况下将存储的一些日期对象复制到存储的日期对象中?我查看了 Oracle 的文档,并没有看到可以接受日期对象或任何方法数据的构造函数可以实现这一点。
code snippet:
代码片段:
do{
d=rawData.mDate[i].getDay();
da=rawData.mDate[i];
datept=i;
do{
vol+=rawData.mVol[i];
pt+=rawData.mPt[i];
c++;
i++;
if (i>=rawData.getSize())
break;
} while(d==rawData.mDate[i].getDay());
// this IS NOT WORKING BECOUSE IT IS A REFRENCE AND RawData gets loaded with new dates,
// Thus chnaging the value in mDate
mDate[ii]=da;
mVol[ii]=vol;
mPt[ii]=pt/c;
if (first)
{
smallest=biggest=pt/c;
first=false;
}
else
{
double temp=pt/c;
if (temp<smallest)
smallest=temp;
if (temp>biggest)
biggest=temp;
}
ii++;
} while(i<rawData.getSize());
采纳答案by Adam
You could use getTime() and passing it into the Date(time) constructor. This is only required because Date is mutable.
您可以使用 getTime() 并将其传递给 Date(time) 构造函数。这只是必需的,因为 Date 是可变的。
Date original = new Date();
Date copy = new Date(original.getTime());
If you're using Java 8 try using the new java.time APIwhich uses immutable objects. So no need to copy/clone.
如果您使用的是 Java 8,请尝试使用使用不可变对象的新java.time API。所以不需要复制/克隆。
回答by Michael Murray
If possible, try switching to using Joda Time instead of the built in Date type.
如果可能,尝试切换到使用 Joda Time 而不是内置的 Date 类型。
http://www.joda.org/joda-time/
http://www.joda.org/joda-time/
DateTime from Joda has a copy constructor, and is generally nicer to work with since DateTime is not mutable.
Joda 的 DateTime 有一个复制构造函数,并且由于 DateTime 不可变,因此通常更易于使用。
Otherwise you could try:
否则你可以尝试:
Date newDate = new Date(oldDate.getTime());
回答by Nicolas Henneaux
With Java 8you can use the following nullsafe code.
在Java 8 中,您可以使用以下 nullsafe 代码。
Optional.ofNullable(oldDate)
.map(Date::getTime)
.map(Date::new)
.orElse(null)