01: /*
02: * Created on Jan 15, 2005
03: */
04: package net.kildenpedersen.util;
05:
06: import java.util.ArrayList;
07: import java.util.Collection;
08: import java.util.Collections;
09:
10: /**
11: * A flexible ArrayList.
12: * Allows setting and adding of arbitrary indexed positions.
13: * Will automatically expand list with <code>null</null> if index is less than size.
14: *
15: * @author Nils Kilden-Pedersen
16: */
17: public final class ExpandingArrayList extends ArrayList {
18:
19: /**
20: * @inheritDoc
21: */
22: public ExpandingArrayList() {
23: super ();
24: }
25:
26: /**
27: * @inheritDoc
28: * @param c
29: */
30: public ExpandingArrayList(Collection c) {
31: super (c);
32: }
33:
34: /**
35: * @inheritDoc
36: * @param initialCapacity
37: */
38: public ExpandingArrayList(int initialCapacity) {
39: super (initialCapacity);
40: }
41:
42: private void adjust(int index) {
43: int difference = (index - size()) + 1;
44:
45: if (difference < 1) {
46: return;
47: }
48:
49: if (difference == 1) {
50: add(null);
51: } else {
52: addAll(Collections.nCopies(difference, null));
53: }
54: }
55:
56: /**
57: * Add element at index, and expand list if necessary.
58: * @param index
59: * @param element
60: * @see java.util.List#add(int, java.lang.Object)
61: */
62: public void add(int index, Object element) {
63: adjust(index);
64: super .add(index, element);
65: }
66:
67: /**
68: * @inheritDoc
69: * @see java.util.ArrayList#get(int)
70: */
71: public Object get(int index) {
72: if (index >= size()) {
73: return null;
74: }
75: return super .get(index);
76: }
77:
78: /**
79: * Set element at index, and expand list if necessary.
80: * @param index
81: * @param element
82: * @return replaced element
83: * @see java.util.List#set(int, java.lang.Object)
84: */
85: public Object set(int index, Object element) {
86: adjust(index);
87: return super .set(index, element);
88: }
89:
90: /**
91: * @inheritDoc
92: * @see java.util.ArrayList#addAll(int, java.util.Collection)
93: */
94: public boolean addAll(int index, Collection c) {
95: adjust(index);
96: return super.addAll(index, c);
97: }
98: }
|