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 package org.nuiton.util;
33
34 import java.lang.reflect.Array;
35 import java.util.Collection;
36
37 public class ArrayUtil {
38
39 public static int[] asIntArray(String[] a) {
40 int[] result = new int[a.length];
41 for (int i = 0; i < a.length; i++) {
42 result[i] = StringUtil.toInt(a[i]);
43 }
44 return result;
45 }
46
47
48
49
50
51
52
53
54
55
56
57 public static int[] sum(int[] a, int[] b) {
58 if (a == null || b == null || a.length != b.length) {
59 throw new IllegalArgumentException("Au moins des tableaux est null ou les tableaux ne font pas la même taille");
60 }
61 int[] result = new int[a.length];
62 for (int i = 0; i < a.length; i++) {
63 result[i] = a[i] + b[i];
64 }
65 return result;
66 }
67
68 public static int[] concat(int[]... tabs) {
69 int length = 0;
70 for (int[] tab : tabs) {
71 if (tab != null) {
72 length += tab.length;
73 }
74 }
75 int[] result = new int[length];
76 length = 0;
77 for (int[] tab : tabs) {
78 if (tab != null) {
79 System.arraycopy(tab, 0, result, length, tab.length);
80 length += tab.length;
81 }
82 }
83 return result;
84 }
85
86
87
88
89
90
91
92
93
94
95
96 public static Object[] concat(Object[]... tabs) {
97 Object[] result = null;
98 Class<?> clazz = null;
99 int length = 0;
100 for (Object[] tab : tabs) {
101 if (tab != null) {
102 length += tab.length;
103 Class<?> tmp = tab.getClass().getComponentType();
104 if (clazz == null) {
105 clazz = tmp;
106 } else if (tmp.isAssignableFrom(clazz)) {
107 clazz = tmp;
108 } else if (clazz.isAssignableFrom(tmp)) {
109
110 } else {
111 clazz = Object.class;
112 }
113 }
114 }
115
116 if (clazz != null) {
117 result = (Object[]) Array.newInstance(clazz, length);
118 length = 0;
119 for (Object[] tab : tabs) {
120 if (tab != null) {
121 System.arraycopy(tab, 0, result, length, tab.length);
122 length += tab.length;
123 }
124 }
125 }
126 return result;
127 }
128
129
130
131
132
133
134
135
136
137
138
139 @SuppressWarnings("unchecked")
140 public static <E, F extends E> E[] concatElems(E[] tab, F... elems) {
141 E[] result;
142 result = (E[]) concat(tab, elems);
143 return result;
144 }
145
146
147
148
149
150
151
152
153
154
155 public static <A> A search(Object[] tab, Class<A> clazz) {
156 A result = null;
157 for (Object o : tab) {
158 if (clazz.isInstance(o)) {
159 result = clazz.cast(o);
160 }
161 }
162 return result;
163 }
164
165 @SuppressWarnings({"unchecked"})
166 public static <T> T[] toArray(Collection list, Class<T> clazz) {
167 T[] result = (T[]) Array.newInstance(clazz, list == null ? 0 : list.size());
168 int i = 0;
169 for (Object o : list) {
170 result[i++] = (T) o;
171 }
172 return result;
173 }
174 }
175