为什么不能将值从一个XYSeriesCollection复制到另一个? [英] Why can't I copy a value from one XYSeriesCollection to other?
问题描述
我正在使用JFreeChart在Java swing中创建图像直方图.为了创建它,我遍历所有像素以获得所有颜色.根据大小和位深度,它需要一些时间.
I'm using JFreeChart to create an image histogram in java swing. In order to create it I iterate over all pixels to get all the colors. Depending on the size and bit depth it takes some time.
一旦我拥有所有数据,就将其放入XYSeriesCollection变量中.为了能够稍后显示和隐藏某些系列,我保存了该变量的副本.
Once I have all the data I put it into a XYSeriesCollection variable. To be able to show and hide some series latter I save a copy of that variable.
我的问题是,如果我这样做:
My problem is that if I do it like this:
final XYSeriesCollection data = createHistogram();
final XYSeriesCollection dataCopy = createHistogram();
它可以正常工作,但是效率不高,因为我必须遍历所有像素,这需要一段时间.
It works without any problem, but it is not efficient, as I have to iterate over all pixels and that takes a while.
如果我只是这样复制它:
If I just copy it like this:
final XYSeriesCollection data = createHistogram();
final XYSeriesCollection dataCopy = data;
执行代码时出现此异常:
When I execute the code I get this exception:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Series index out of bounds
at org.jfree.data.xy.XYSeriesCollection.getSeries(XYSeriesCollection.java:263)
我认为这是因为当我从数据中删除系列时,它们如何也从dataCopy中删除,但是那不应该完全不同吗?我只是使用这种方法:
I think that this is because when I delete the series from data some how they also get deleted from dataCopy but shouldn't those be completely different? I just work with this methods:
data.removeAllseries();
data.addSeries(dataCopy.getSeries(index));
例如,如果我创建:
int x = 5;
int y = x;
x=0;
System.out.println(y)
输出仍应为5,与x无关.我在做什么或假设那是错误的?
The output should still be 5 and it doesn't matter what I did with x. What am I doing or assuming that is wrong?
谢谢.
推荐答案
请注意 浅与深副本.您的示例dataCopy = data
复制了 浅 .使用数据集的clone()
方法制作 深 副本:
Note the difference between shallow versus deep copy. Your example, dataCopy = data
, makes a shallow copy. Use the dataset's clone()
method to make a deep copy:
XYSeriesCollection dataCopy = (XYSeriesCollection) data.clone();
You can see how clone()
is implemented here. The fragment below creates a series, clones it, and updates the original to illustrate the effect.
代码:
XYSeriesCollection data = new XYSeriesCollection();
XYSeries series = new XYSeries("Test");
data.addSeries(series);
series.add(1, 42);
System.out.println(data.getSeries(0).getY(0));
XYSeriesCollection dataCopy = (XYSeriesCollection) data.clone();
series.updateByIndex(0, 21.0);
System.out.println(data.getSeries(0).getY(0));
System.out.println(dataCopy.getSeries(0).getY(0));
控制台:
42.0
21.0
42.0
还请考虑此处所示的方法,该方法可能更快.
Also consider the approach shown here, which may be faster.
这篇关于为什么不能将值从一个XYSeriesCollection复制到另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!