Why can't I copy a value from one XYSeriesCollection to another?

I am using JFreeChart to create a histogram of an image in java swing. To create it, I iterate over all the pixels to get all the colors. Depending on the size and depth of the bit, some time is required.

As soon as I have all the data, I put it in the XYSeriesCollection variable. To be able to show and hide some series, I keep a copy of this variable.

My problem is if I do it like this:

final XYSeriesCollection data = createHistogram(); final XYSeriesCollection dataCopy = createHistogram(); 

It works without any problems, but it is inefficient as I have to iterate over all the pixels, and this takes some time.

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) 

I think this is because when I delete a series from data, some of them are also deleted from dataCopy, but should they not be completely different? I just work with these methods:

 data.removeAllseries(); data.addSeries(dataCopy.getSeries(index)); 

For example, if I create:

 int x = 5; int y = x; x=0; System.out.println(y) 

The output should be 5, and it doesn't matter what I did with x. What am I doing or suppose this is wrong?

Thanks.

+1
source share
1 answer

Note the difference between shallow and deep copies . Your example, dataCopy = data , makes the copy shallow . Use the dataset clone() method to make a deep copy:

 XYSeriesCollection dataCopy = (XYSeriesCollection) data.clone(); 

You can see how clone() implemented here . The snippet below creates a series, clones it, and updates the original to illustrate the effect.

code:

 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)); 

Console:

 42.0 21.0 42.0 

Also consider the approach below, which can be faster.

+1
source

Source: https://habr.com/ru/post/982499/


All Articles