Search code examples
javalisttime-seriesjfreechart

Adding to a series within a List in Java


I'm using JFreeChart to do some graphing. One of the classes for managing your data is TimeSeries. There is also a class TimeSeriesCollection which has a List of TimeSeries in it.

TimeSeries has a method add() that makes it easy to throw a new datapoint at the end, whereas TimeSeriesCollection does not. I wanted to add a method into TimeSeriesCollection that would call the add() function for each of its TimeSeries, however, I'm not very familiar working with Lists in Java.

From what I've seen, one possible method would be to get() each TimeSeries, call it's add() method, and then set() it back into the List. But this seems pretty inefficient. Is it possible to directly call methods of elements within a List?


Solution

  • You can use a foreach loop to call the add method for every TimeSeries:

    for (TimeSeries timeSeries: TimeSeriesCollection.timeSeriesList) {
      timeSeries.add(datapoint);
    }
    

    You don't even have to set the objects, you modify back into the list in TimeSeriesCollection, because you don't create a copy of the elements. You are directly modifying the object references in the list.