commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
Subject Suggestion to imrovement of org.apache.commons.lang.ArrayUtils
Date Tue, 06 Jul 2004 19:38:35 GMT

I'm currently working on a class I've called ArrayConverter. I have tried 
to make some methods which I find helpful, and you might find it 
The most important one is perhaps the cast-method:

         * The method can cast an array from one type to another. One
         * typical case is from Object[] to String[]. This wil work
         * within limits. You can probably cast from almost any object
         * to String, but then your objects should (in most cases) 
         * toString() correctly, at least if you want the casting to make
         * sense. You can cast from any kind of object to every
         * other kind of object, if you have a correct constructor
         * in the object to casting to. Casting between primitives
         * and primitive wrappers (back and forth) should be allright.
         * Some casts are impossible (Map[] --> List[]), because we
         * can't write a constructor (List(Map map)) but that's obvious. 
         * The exceptions are written to standard out. This should
         * be changed in the future.
        public static Object cast(Object array, Class type) {

The reason for making this method was initially a desire to quickly 
iterate over a Map with String-values, like this: (yes, I don't like using 

Map stringMap;
String[] values = (String[]) cast(stringMap.values().toArray(), 
for (int i=0;i<values.length;i++) {
        // perhaps do some String-manipulation on the values

....which is one usecase.

The other methods I've made is not very clever, but nice enough:

         * The method is just a wrapper around System.arraycopy, because 
         * is to complicated to use that method directly (that's what I 
        public static Object addArrays(Object array1, Object array2) {
         * Converts from an array to an ArrayList-object.
        public static List toArrayList(Object array) {
         * Converts from an array to an Vector-object. (ThreadSafe)
        public static List toVector(Object array) {
         * Converts from a list to an array. Uses the cast-method
         * in this method, so all the limitations of that method
         * also applies here.
        public static Object toArray(List list, Class type) {

There are two reasons why I write this mail:

1. I would like to contribute something to the open-source-community.
2. I would like to improve the quality of the cast()-method, I suspect 
there maybe many possibilites for improvement.

I have supplied a main-method in the java-code, so it should be easy to 
test. I'm using WSAD 5.1.1, and my code
is based on the java.lang.reflect.Array-class. I'm not sure how far back 
this class is supported (concerning JDK), 
but I suspect it's an "old" class.

Morten Simonsen

View raw message