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
65 public static<T> T[] addToArray(T[] array, T item, Class<?> type)
66 {
67 if (array==null)
68 {
69 if (type==null && item!=null)
70 type= item.getClass();
71 @SuppressWarnings("unchecked")
72 T[] na = (T[])Array.newInstance(type, 1);
73 na[0]=item;
74 return na;
75 }
76 else
77 {
78 T[] na = Arrays.copyOf(array,array.length+1);
79 na[array.length]=item;
80 return na;
81 }
82 }
83
84
85
86
87
88
89
90
91
92 public static<T> T[] prependToArray(T item, T[] array, Class<?> type)
93 {
94 if (array==null)
95 {
96 if (type==null && item!=null)
97 type= item.getClass();
98 @SuppressWarnings("unchecked")
99 T[] na = (T[])Array.newInstance(type, 1);
100 na[0]=item;
101 return na;
102 }
103 else
104 {
105 Class<?> c = array.getClass().getComponentType();
106 @SuppressWarnings("unchecked")
107 T[] na = (T[])Array.newInstance(c, Array.getLength(array)+1);
108 System.arraycopy(array, 0, na, 1, array.length);
109 na[0]=item;
110 return na;
111 }
112 }
113
114
115
116
117
118
119
120 public static<E> List<E> asMutableList(E[] array)
121 {
122 if (array==null || array.length==0)
123 return new ArrayList<E>();
124 return new ArrayList<E>(Arrays.asList(array));
125 }
126
127
128 public static <T> T[] removeNulls(T[] array)
129 {
130 for (T t : array)
131 {
132 if (t==null)
133 {
134 List<T> list = new ArrayList<>();
135 for (T t2:array)
136 if (t2!=null)
137 list.add(t2);
138 return list.toArray(Arrays.copyOf(array,list.size()));
139 }
140 }
141 return array;
142 }
143
144 }
145