Skip to main content
summaryrefslogtreecommitdiffstats
blob: 14c48d5240f103bf93a800c3232d0bc0423067c3 (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
98
99
100
101
102
103
104
105
106
/**
 * Copyright (c) 2004 - 2011 Eike Stepper (Berlin, 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 3.0
 */
public abstract class FastList<E>
{
  protected E[] elements;

  public FastList()
  {
  }

  public boolean isEmpty()
  {
    return elements == null;
  }

  public E[] get()
  {
    return elements;
  }

  public synchronized void add(E element)
  {
    if (elements == null)
    {
      E[] array = newArray(1);
      array[0] = element;
      elements = array;
      firstElementAdded();
    }
    else
    {
      int length = elements.length;
      E[] array = newArray(length + 1);
      System.arraycopy(elements, 0, array, 0, length);
      array[length] = element;
      elements = array;
    }
  }

  public synchronized boolean remove(E element)
  {
    if (elements != null)
    {
      int length = elements.length;
      if (length == 1)
      {
        if (elements[0] == element)
        {
          elements = null;
          lastElementRemoved();
          return true;
        }
      }
      else
      {
        for (int i = 0; i < length; i++)
        {
          E e = elements[i];
          if (e == element)
          {
            E[] array = newArray(length - 1);

            if (i > 0)
            {
              System.arraycopy(elements, 0, array, 0, i);
            }

            if (i + 1 <= length - 1)
            {
              System.arraycopy(elements, i + 1, array, i, length - 1 - i);
            }

            elements = array;
            return true;
          }
        }
      }
    }

    return false;
  }

  protected void firstElementAdded()
  {
  }

  protected void lastElementRemoved()
  {
  }

  protected abstract E[] newArray(int length);
}

Back to the top