1 package org.exolab.castor.mapping.loader.collection.handler;
2
3 import java.lang.reflect.Array;
4 import java.util.Enumeration;
5
6 import org.exolab.castor.mapping.CollectionHandler;
7 import org.exolab.castor.mapping.loader.CollectionHandlers;
8 import org.exolab.castor.mapping.loader.J1CollectionHandlers.ArrayEnumerator;
9
10 public final class ArrayCollectionHandler<T> implements CollectionHandler<T> {
11 public Object add(Object collection, T object) {
12 if (collection == null) {
13
14
15
16
17 Object newArray = Array.newInstance(object.getClass(), 1);
18 Array.set(newArray, 0, object);
19 return newArray;
20 }
21
22 Class<?> type = collection.getClass();
23 if (!type.isArray()) {
24 String err = "J1CollectionHandlers.array#add: type "
25 + "mismatch, expecting an array, instead received: ";
26 err += type.getName();
27 throw new IllegalArgumentException(err);
28 }
29
30 type = type.getComponentType();
31
32 Object newArray = Array.newInstance(type, Array.getLength(collection) + 1);
33
34 for (int i = 0; i < Array.getLength(collection); ++i)
35 Array.set(newArray, i, Array.get(collection, i));
36
37 Array.set(newArray, Array.getLength(collection), object);
38
39 return newArray;
40
41 }
42
43 public Enumeration<T> elements(Object collection) {
44 if (collection == null)
45 return new CollectionHandlers.EmptyEnumerator<T>();
46 return new ArrayEnumerator<T>(collection);
47 }
48
49 public int size(Object collection) {
50 if (collection == null)
51 return 0;
52 return Array.getLength(collection);
53 }
54
55 public Object clear(Object collection) {
56 if (collection == null) {
57 return null;
58 }
59 Class<?> type = collection.getClass();
60 if (!type.isArray()) {
61 String err = "J1CollectionHandlers.array#add: type "
62 + "mismatch, expecting an array, instead received: ";
63 err += type.getName();
64 throw new IllegalArgumentException(err);
65 }
66 type = type.getComponentType();
67 return Array.newInstance(type, 0);
68 }
69
70 public String toString() {
71 return "Object[]";
72 }
73 }