Skip to main content
summaryrefslogtreecommitdiffstats
blob: 84de914308fec2bb707090de8d7239fc6ac50b9a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/***************************************************************************
 * Copyright (c) 2004 - 2008 Eike Stepper (Germany) and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *    Eike Stepper - initial API and implementation
 **************************************************************************/
package org.eclipse.net4j.util.collection;

/**
 * @author Eike Stepper
 * @since 2.0
 */
public class DynamicArray<E>
{
  private Object[] elements;

  public DynamicArray()
  {
  }

  public int add(E element)
  {
    int length = elements.length;
    for (int i = 0; i < length; i++)
    {
      if (elements[i] == null)
      {
        elements[i] = element;
        return i;
      }
    }

    grow(length);
    elements[length] = element;
    return length;
  }

  @SuppressWarnings("unchecked")
  public E add(int index, E element)
  {
    grow(index);
    Object old = elements[index];
    elements[index] = element;
    return (E)old;
  }

  @SuppressWarnings("unchecked")
  public E remove(int index)
  {
    Object old = elements[index];
    if (old != null)
    {
      elements[index] = null;
      shrink();
    }

    return (E)old;
  }

  @SuppressWarnings("unchecked")
  public E get(int index)
  {
    return (E)elements[index];
  }

  private void grow(int index)
  {
    if (index >= elements.length)
    {
      Object[] newChannels = new Object[index + 1];
      System.arraycopy(elements, 0, newChannels, 0, elements.length);
      elements = newChannels;
    }
  }

  private void shrink()
  {
    boolean shrink = false;
    int lastIndex = elements.length - 1;
    while (lastIndex > 0 && (shrink = elements[lastIndex] == null))
    {
      --lastIndex;
    }

    if (shrink)
    {
      int newLength = lastIndex + 1;
      Object[] newChannels = new Object[newLength];
      System.arraycopy(elements, 0, newChannels, 0, newLength);
      elements = newChannels;
    }
  }
}

Back to the top