1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.eclipse.jetty.util;
20
21 import java.io.Serializable;
22 import java.lang.reflect.Array;
23 import java.util.ArrayList;
24 import java.util.Arrays;
25 import java.util.List;
26
27
28
29
30
31 public class ArrayUtil
32 implements Cloneable, Serializable
33 {
34
35
36 public static<T> T[] removeFromArray(T[] array, Object item)
37 {
38 if (item==null || array==null)
39 return array;
40 for (int i=array.length;i-->0;)
41 {
42 if (item.equals(array[i]))
43 {
44 Class<?> c = array==null?item.getClass():array.getClass().getComponentType();
45 @SuppressWarnings("unchecked")
46 T[] na = (T[])Array.newInstance(c, Array.getLength(array)-1);
47 if (i>0)
48 System.arraycopy(array, 0, na, 0, i);
49 if (i+1<array.length)
50 System.arraycopy(array, i+1, na, i, array.length-(i+1));
51 return na;
52 }
53 }
54 return array;
55 }
56
57
58
59
60
61
62
63
64 public static<T> T[] addToArray(T[] array, T item, Class<?> type)
65 {
66 if (array==null)
67 {
68 if (type==null && item!=null)
69 type= item.getClass();
70 @SuppressWarnings("unchecked")
71 T[] na = (T[])Array.newInstance(type, 1);
72 na[0]=item;
73 return na;
74 }
75 else
76 {
77 T[] na = Arrays.copyOf(array,array.length+1);
78 na[array.length]=item;
79 return na;
80 }
81 }
82
83
84
85
86
87
88
89
90 public static<T> T[] prependToArray(T item, T[] array, Class<?> type)
91 {
92 if (array==null)
93 {
94 if (type==null && item!=null)
95 type= item.getClass();
96 @SuppressWarnings("unchecked")
97 T[] na = (T[])Array.newInstance(type, 1);
98 na[0]=item;
99 return na;
100 }
101 else
102 {
103 Class<?> c = array.getClass().getComponentType();
104 @SuppressWarnings("unchecked")
105 T[] na = (T[])Array.newInstance(c, Array.getLength(array)+1);
106 System.arraycopy(array, 0, na, 1, array.length);
107 na[0]=item;
108 return na;
109 }
110 }
111
112
113
114
115
116
117 public static<E> List<E> asMutableList(E[] array)
118 {
119 if (array==null || array.length==0)
120 return new ArrayList<E>();
121 return new ArrayList<E>(Arrays.asList(array));
122 }
123
124
125 public static <T> T[] removeNulls(T[] array)
126 {
127 for (T t : array)
128 {
129 if (t==null)
130 {
131 List<T> list = new ArrayList<>();
132 for (T t2:array)
133 if (t2!=null)
134 list.add(t2);
135 return list.toArray(Arrays.copyOf(array,list.size()));
136 }
137 }
138 return array;
139 }
140
141 }
142