01: /*
02: * Copyright (C) Jakub Neubauer, 2007
03: *
04: * This file is part of TaskBlocks
05: *
06: * TaskBlocks is free software; you can redistribute it and/or modify
07: * it under the terms of the GNU General Public License as published by
08: * the Free Software Foundation; either version 3 of the License, or
09: * (at your option) any later version.
10: *
11: * TaskBlocks is distributed in the hope that it will be useful,
12: * but WITHOUT ANY WARRANTY; without even the implied warranty of
13: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14: * GNU General Public License for more details.
15: *
16: * You should have received a copy of the GNU General Public License
17: * along with this program. If not, see <http://www.gnu.org/licenses/>.
18: */
19:
20: package taskblocks;
21:
22: import java.lang.reflect.Array;
23:
24: /**
25: * Set of utilities used to manipulate arrays.
26: *
27: * @author j.neubauer
28: * @since 11.1.2007
29: */
30: public class ArrayUtils {
31:
32: /**
33: * Creates new array of the same type as given array and adds specified member
34: * to the end of new array.
35: *
36: * @param array
37: * @param member
38: * @return new array with member appened
39: */
40: public static Object[] addToArray(Object[] array, Object member) {
41: Object[] newArray = (Object[]) Array.newInstance(array
42: .getClass().getComponentType(), array.length + 1);
43: System.arraycopy(array, 0, newArray, 0, array.length);
44: newArray[array.length] = member;
45: return newArray;
46: }
47:
48: /**
49: * Finds member in array and if finds it, creates the same array without this member.
50: *
51: * @param array
52: * @param member
53: * @return new array without member or the old array if member wasn't found
54: */
55: public static Object[] removeFromArray(Object[] array, Object member) {
56: int i;
57: for (i = 0; i < array.length; i++) {
58: if (array[i] == member) {
59: break;
60: }
61: }
62: // if we found the listener, construct new arrray without it.
63: if (i < array.length) {
64: Object[] newArray = (Object[]) Array.newInstance(array
65: .getClass().getComponentType(), array.length - 1);
66: System.arraycopy(array, 0, newArray, 0, i);
67: System.arraycopy(array, i + 1, newArray, i, array.length
68: - i - 1);
69: return newArray;
70: }
71: return array;
72: }
73:
74: public static Object[] removeFromArray(Object[] array, int i) {
75: if (i < 0 || i >= array.length) {
76: throw new IndexOutOfBoundsException();
77: }
78: Object[] newArray = (Object[]) Array.newInstance(array
79: .getClass().getComponentType(), array.length - 1);
80: System.arraycopy(array, 0, newArray, 0, i);
81: System.arraycopy(array, i + 1, newArray, i, array.length - i
82: - 1);
83: return newArray;
84: }
85: }
|