001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2020, by Object Refinery Limited and Contributors.
006 *
007 * Project Info:  http://www.jfree.org/jfreechart/index.html
008 *
009 * This library is free software; you can redistribute it and/or modify it
010 * under the terms of the GNU Lesser General Public License as published by
011 * the Free Software Foundation; either version 2.1 of the License, or
012 * (at your option) any later version.
013 *
014 * This library is distributed in the hope that it will be useful, but
015 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
016 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
017 * License for more details.
018 *
019 * You should have received a copy of the GNU Lesser General Public
020 * License along with this library; if not, write to the Free Software
021 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301,
022 * USA.
023 *
024 * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. 
025 * Other names may be trademarks of their respective owners.]
026 *
027 * -------------------------
028 * DefaultKeyedValues2D.java
029 * -------------------------
030 * (C) Copyright 2002-2016, by Object Refinery Limited.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   Andreas Schroeder;
034 *
035 * Changes
036 * -------
037 * 28-Oct-2002 : Version 1 (DG);
038 * 21-Jan-2003 : Updated Javadocs (DG);
039 * 13-Mar-2003 : Implemented Serializable (DG);
040 * 18-Aug-2003 : Implemented Cloneable (DG);
041 * 31-Mar-2004 : Made the rows optionally sortable by a flag (AS);
042 * 01-Apr-2004 : Implemented remove method (AS);
043 * 05-Apr-2004 : Added clear() method (DG);
044 * 15-Sep-2004 : Fixed clone() method (DG);
045 * 12-Jan-2005 : Fixed bug in getValue() method (DG);
046 * 23-Mar-2005 : Implemented PublicCloneable (DG);
047 * 09-Jun-2005 : Modified getValue() method to throw exception for unknown
048 *               keys (DG);
049 * ------------- JFREECHART 1.0.x ---------------------------------------------
050 * 18-Jan-2007 : Fixed bug in getValue() method (DG);
051 * 30-Mar-2007 : Fixed bug 1690654, problem with removeValue() (DG);
052 * 21-Nov-2007 : Fixed bug (1835955) in removeColumn(Comparable) method (DG);
053 * 23-Nov-2007 : Added argument checks to removeRow(Comparable) to make it
054 *               consistent with the removeRow(Comparable) method (DG);
055 * 03-Jul-2013 : Use ParamChecks (DG);
056 * 
057 */
058
059package org.jfree.data;
060
061import java.io.Serializable;
062import java.util.Collections;
063import java.util.Iterator;
064import java.util.List;
065import org.jfree.chart.util.ObjectUtils;
066import org.jfree.chart.util.Args;
067import org.jfree.chart.util.PublicCloneable;
068
069/**
070 * A data structure that stores zero, one or many values, where each value
071 * is associated with two keys (a 'row' key and a 'column' key).  The keys
072 * should be (a) instances of {@link Comparable} and (b) immutable.
073 */
074public class DefaultKeyedValues2D implements KeyedValues2D, PublicCloneable,
075        Cloneable, Serializable {
076
077    /** For serialization. */
078    private static final long serialVersionUID = -5514169970951994748L;
079
080    /** The row keys. */
081    private List rowKeys;
082
083    /** The column keys. */
084    private List columnKeys;
085
086    /** The row data. */
087    private List rows;
088
089    /** If the row keys should be sorted by their comparable order. */
090    private boolean sortRowKeys;
091
092    /**
093     * Creates a new instance (initially empty).
094     */
095    public DefaultKeyedValues2D() {
096        this(false);
097    }
098
099    /**
100     * Creates a new instance (initially empty).
101     *
102     * @param sortRowKeys  if the row keys should be sorted.
103     */
104    public DefaultKeyedValues2D(boolean sortRowKeys) {
105        this.rowKeys = new java.util.ArrayList();
106        this.columnKeys = new java.util.ArrayList();
107        this.rows = new java.util.ArrayList();
108        this.sortRowKeys = sortRowKeys;
109    }
110
111    /**
112     * Returns the row count.
113     *
114     * @return The row count.
115     *
116     * @see #getColumnCount()
117     */
118    @Override
119    public int getRowCount() {
120        return this.rowKeys.size();
121    }
122
123    /**
124     * Returns the column count.
125     *
126     * @return The column count.
127     *
128     * @see #getRowCount()
129     */
130    @Override
131    public int getColumnCount() {
132        return this.columnKeys.size();
133    }
134
135    /**
136     * Returns the value for a given row and column.
137     *
138     * @param row  the row index.
139     * @param column  the column index.
140     *
141     * @return The value.
142     *
143     * @see #getValue(Comparable, Comparable)
144     */
145    @Override
146    public Number getValue(int row, int column) {
147        Number result = null;
148        DefaultKeyedValues rowData = (DefaultKeyedValues) this.rows.get(row);
149        if (rowData != null) {
150            Comparable columnKey = (Comparable) this.columnKeys.get(column);
151            // the row may not have an entry for this key, in which case the
152            // return value is null
153            int index = rowData.getIndex(columnKey);
154            if (index >= 0) {
155                result = rowData.getValue(index);
156            }
157        }
158        return result;
159    }
160
161    /**
162     * Returns the key for a given row.
163     *
164     * @param row  the row index (in the range 0 to {@link #getRowCount()} - 1).
165     *
166     * @return The row key.
167     *
168     * @see #getRowIndex(Comparable)
169     * @see #getColumnKey(int)
170     */
171    @Override
172    public Comparable getRowKey(int row) {
173        return (Comparable) this.rowKeys.get(row);
174    }
175
176    /**
177     * Returns the row index for a given key.
178     *
179     * @param key  the key ({@code null} not permitted).
180     *
181     * @return The row index.
182     *
183     * @see #getRowKey(int)
184     * @see #getColumnIndex(Comparable)
185     */
186    @Override
187    public int getRowIndex(Comparable key) {
188        Args.nullNotPermitted(key, "key");
189        if (this.sortRowKeys) {
190            return Collections.binarySearch(this.rowKeys, key);
191        }
192        else {
193            return this.rowKeys.indexOf(key);
194        }
195    }
196
197    /**
198     * Returns the row keys in an unmodifiable list.
199     *
200     * @return The row keys.
201     *
202     * @see #getColumnKeys()
203     */
204    @Override
205    public List getRowKeys() {
206        return Collections.unmodifiableList(this.rowKeys);
207    }
208
209    /**
210     * Returns the key for a given column.
211     *
212     * @param column  the column (in the range 0 to {@link #getColumnCount()}
213     *     - 1).
214     *
215     * @return The key.
216     *
217     * @see #getColumnIndex(Comparable)
218     * @see #getRowKey(int)
219     */
220    @Override
221    public Comparable getColumnKey(int column) {
222        return (Comparable) this.columnKeys.get(column);
223    }
224
225    /**
226     * Returns the column index for a given key.
227     *
228     * @param key  the key ({@code null} not permitted).
229     *
230     * @return The column index.
231     *
232     * @see #getColumnKey(int)
233     * @see #getRowIndex(Comparable)
234     */
235    @Override
236    public int getColumnIndex(Comparable key) {
237        Args.nullNotPermitted(key, "key");
238        return this.columnKeys.indexOf(key);
239    }
240
241    /**
242     * Returns the column keys in an unmodifiable list.
243     *
244     * @return The column keys.
245     *
246     * @see #getRowKeys()
247     */
248    @Override
249    public List getColumnKeys() {
250        return Collections.unmodifiableList(this.columnKeys);
251    }
252
253    /**
254     * Returns the value for the given row and column keys.  This method will
255     * throw an {@link UnknownKeyException} if either key is not defined in the
256     * data structure.
257     *
258     * @param rowKey  the row key ({@code null} not permitted).
259     * @param columnKey  the column key ({@code null} not permitted).
260     *
261     * @return The value (possibly {@code null}).
262     *
263     * @see #addValue(Number, Comparable, Comparable)
264     * @see #removeValue(Comparable, Comparable)
265     */
266    @Override
267    public Number getValue(Comparable rowKey, Comparable columnKey) {
268        Args.nullNotPermitted(rowKey, "rowKey");
269        Args.nullNotPermitted(columnKey, "columnKey");
270
271        // check that the column key is defined in the 2D structure
272        if (!(this.columnKeys.contains(columnKey))) {
273            throw new UnknownKeyException("Unrecognised columnKey: "
274                    + columnKey);
275        }
276
277        // now fetch the row data - need to bear in mind that the row
278        // structure may not have an entry for the column key, but that we
279        // have already checked that the key is valid for the 2D structure
280        int row = getRowIndex(rowKey);
281        if (row >= 0) {
282            DefaultKeyedValues rowData
283                = (DefaultKeyedValues) this.rows.get(row);
284            int col = rowData.getIndex(columnKey);
285            return (col >= 0 ? rowData.getValue(col) : null);
286        }
287        else {
288            throw new UnknownKeyException("Unrecognised rowKey: " + rowKey);
289        }
290    }
291
292    /**
293     * Adds a value to the table.  Performs the same function as
294     * #setValue(Number, Comparable, Comparable).
295     *
296     * @param value  the value ({@code null} permitted).
297     * @param rowKey  the row key ({@code null} not permitted).
298     * @param columnKey  the column key ({@code null} not permitted).
299     *
300     * @see #setValue(Number, Comparable, Comparable)
301     * @see #removeValue(Comparable, Comparable)
302     */
303    public void addValue(Number value, Comparable rowKey,
304                         Comparable columnKey) {
305        // defer argument checking
306        setValue(value, rowKey, columnKey);
307    }
308
309    /**
310     * Adds or updates a value.
311     *
312     * @param value  the value ({@code null} permitted).
313     * @param rowKey  the row key ({@code null} not permitted).
314     * @param columnKey  the column key ({@code null} not permitted).
315     *
316     * @see #addValue(Number, Comparable, Comparable)
317     * @see #removeValue(Comparable, Comparable)
318     */
319    public void setValue(Number value, Comparable rowKey,
320                         Comparable columnKey) {
321
322        DefaultKeyedValues row;
323        int rowIndex = getRowIndex(rowKey);
324
325        if (rowIndex >= 0) {
326            row = (DefaultKeyedValues) this.rows.get(rowIndex);
327        }
328        else {
329            row = new DefaultKeyedValues();
330            if (this.sortRowKeys) {
331                rowIndex = -rowIndex - 1;
332                this.rowKeys.add(rowIndex, rowKey);
333                this.rows.add(rowIndex, row);
334            }
335            else {
336                this.rowKeys.add(rowKey);
337                this.rows.add(row);
338            }
339        }
340        row.setValue(columnKey, value);
341
342        int columnIndex = this.columnKeys.indexOf(columnKey);
343        if (columnIndex < 0) {
344            this.columnKeys.add(columnKey);
345        }
346    }
347
348    /**
349     * Removes a value from the table by setting it to {@code null}.  If
350     * all the values in the specified row and/or column are now
351     * {@code null}, the row and/or column is removed from the table.
352     *
353     * @param rowKey  the row key ({@code null} not permitted).
354     * @param columnKey  the column key ({@code null} not permitted).
355     *
356     * @see #addValue(Number, Comparable, Comparable)
357     */
358    public void removeValue(Comparable rowKey, Comparable columnKey) {
359        setValue(null, rowKey, columnKey);
360
361        // 1. check whether the row is now empty.
362        boolean allNull = true;
363        int rowIndex = getRowIndex(rowKey);
364        DefaultKeyedValues row = (DefaultKeyedValues) this.rows.get(rowIndex);
365
366        for (int item = 0, itemCount = row.getItemCount(); item < itemCount;
367             item++) {
368            if (row.getValue(item) != null) {
369                allNull = false;
370                break;
371            }
372        }
373
374        if (allNull) {
375            this.rowKeys.remove(rowIndex);
376            this.rows.remove(rowIndex);
377        }
378
379        // 2. check whether the column is now empty.
380        allNull = true;
381        //int columnIndex = getColumnIndex(columnKey);
382
383        for (int item = 0, itemCount = this.rows.size(); item < itemCount;
384             item++) {
385            row = (DefaultKeyedValues) this.rows.get(item);
386            int columnIndex = row.getIndex(columnKey);
387            if (columnIndex >= 0 && row.getValue(columnIndex) != null) {
388                allNull = false;
389                break;
390            }
391        }
392
393        if (allNull) {
394            for (int item = 0, itemCount = this.rows.size(); item < itemCount;
395                 item++) {
396                row = (DefaultKeyedValues) this.rows.get(item);
397                int columnIndex = row.getIndex(columnKey);
398                if (columnIndex >= 0) {
399                    row.removeValue(columnIndex);
400                }
401            }
402            this.columnKeys.remove(columnKey);
403        }
404    }
405
406    /**
407     * Removes a row.
408     *
409     * @param rowIndex  the row index.
410     *
411     * @see #removeRow(Comparable)
412     * @see #removeColumn(int)
413     */
414    public void removeRow(int rowIndex) {
415        this.rowKeys.remove(rowIndex);
416        this.rows.remove(rowIndex);
417    }
418
419    /**
420     * Removes a row from the table.
421     *
422     * @param rowKey  the row key ({@code null} not permitted).
423     *
424     * @see #removeRow(int)
425     * @see #removeColumn(Comparable)
426     *
427     * @throws UnknownKeyException if {@code rowKey} is not defined in the
428     *         table.
429     */
430    public void removeRow(Comparable rowKey) {
431        Args.nullNotPermitted(rowKey, "rowKey");
432        int index = getRowIndex(rowKey);
433        if (index >= 0) {
434            removeRow(index);
435        }
436        else {
437            throw new UnknownKeyException("Unknown key: " + rowKey);
438        }
439    }
440
441    /**
442     * Removes a column.
443     *
444     * @param columnIndex  the column index.
445     *
446     * @see #removeColumn(Comparable)
447     * @see #removeRow(int)
448     */
449    public void removeColumn(int columnIndex) {
450        Comparable columnKey = getColumnKey(columnIndex);
451        removeColumn(columnKey);
452    }
453
454    /**
455     * Removes a column from the table.
456     *
457     * @param columnKey  the column key ({@code null} not permitted).
458     *
459     * @throws UnknownKeyException if the table does not contain a column with
460     *     the specified key.
461     * @throws IllegalArgumentException if {@code columnKey} is
462     *     {@code null}.
463     *
464     * @see #removeColumn(int)
465     * @see #removeRow(Comparable)
466     */
467    public void removeColumn(Comparable columnKey) {
468        Args.nullNotPermitted(columnKey, "columnKey");
469        if (!this.columnKeys.contains(columnKey)) {
470            throw new UnknownKeyException("Unknown key: " + columnKey);
471        }
472        Iterator iterator = this.rows.iterator();
473        while (iterator.hasNext()) {
474            DefaultKeyedValues rowData = (DefaultKeyedValues) iterator.next();
475            int index = rowData.getIndex(columnKey);
476            if (index >= 0) {
477                rowData.removeValue(columnKey);
478            }
479        }
480        this.columnKeys.remove(columnKey);
481    }
482
483    /**
484     * Clears all the data and associated keys.
485     */
486    public void clear() {
487        this.rowKeys.clear();
488        this.columnKeys.clear();
489        this.rows.clear();
490    }
491
492    /**
493     * Tests if this object is equal to another.
494     *
495     * @param o  the other object ({@code null} permitted).
496     *
497     * @return A boolean.
498     */
499    @Override
500    public boolean equals(Object o) {
501
502        if (o == null) {
503            return false;
504        }
505        if (o == this) {
506            return true;
507        }
508
509        if (!(o instanceof KeyedValues2D)) {
510            return false;
511        }
512        KeyedValues2D kv2D = (KeyedValues2D) o;
513        if (!getRowKeys().equals(kv2D.getRowKeys())) {
514            return false;
515        }
516        if (!getColumnKeys().equals(kv2D.getColumnKeys())) {
517            return false;
518        }
519        int rowCount = getRowCount();
520        if (rowCount != kv2D.getRowCount()) {
521            return false;
522        }
523
524        int colCount = getColumnCount();
525        if (colCount != kv2D.getColumnCount()) {
526            return false;
527        }
528
529        for (int r = 0; r < rowCount; r++) {
530            for (int c = 0; c < colCount; c++) {
531                Number v1 = getValue(r, c);
532                Number v2 = kv2D.getValue(r, c);
533                if (v1 == null) {
534                    if (v2 != null) {
535                        return false;
536                    }
537                }
538                else {
539                    if (!v1.equals(v2)) {
540                        return false;
541                    }
542                }
543            }
544        }
545        return true;
546    }
547
548    /**
549     * Returns a hash code.
550     *
551     * @return A hash code.
552     */
553    @Override
554    public int hashCode() {
555        int result;
556        result = this.rowKeys.hashCode();
557        result = 29 * result + this.columnKeys.hashCode();
558        result = 29 * result + this.rows.hashCode();
559        return result;
560    }
561
562    /**
563     * Returns a clone.
564     *
565     * @return A clone.
566     *
567     * @throws CloneNotSupportedException  this class will not throw this
568     *         exception, but subclasses (if any) might.
569     */
570    @Override
571    public Object clone() throws CloneNotSupportedException {
572        DefaultKeyedValues2D clone = (DefaultKeyedValues2D) super.clone();
573        // for the keys, a shallow copy should be fine because keys
574        // should be immutable...
575        clone.columnKeys = new java.util.ArrayList(this.columnKeys);
576        clone.rowKeys = new java.util.ArrayList(this.rowKeys);
577
578        // but the row data requires a deep copy
579        clone.rows = (List) ObjectUtils.deepClone(this.rows);
580        return clone;
581    }
582
583}