com.discovery.darchrow.lang.ArrayUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.discovery.darchrow.lang.ArrayUtil.java

Source

/*
 * Copyright (C) 2008 feilong
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.discovery.darchrow.lang;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;

import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.discovery.darchrow.bean.PropertyUtil;
import com.discovery.darchrow.util.Validator;

/**
 * .
 * 
 * @author feilong
 * @version 1.0 2010-4-16 ?01:00:27
 * @since 1.0.0
 */
public final class ArrayUtil {

    /** The Constant LOGGER. */
    private static final Logger LOGGER = LoggerFactory.getLogger(ArrayUtil.class);

    /** Don't let anyone instantiate this class. */
    private ArrayUtil() {
        //AssertionError?. ?????. ???.
        //see Effective Java 2nd
        throw new AssertionError("No " + getClass().getName() + " instances for you!");
    }

    /**
     * ?.
     * (Returns the value of the indexed component in the specified array object.
     * The value is automatically wrapped in an object if it has a primitive type.)
     *
     * @param <T>
     *            the generic type
     * @param array
     *            
     * @param index
     *            
     * @return ,the (possibly wrapped) value of the indexed component in the specified array
     * @throws ArrayIndexOutOfBoundsException
     *             If the specified {@code index} argument is negative, or if it is greater than or equal to the length of the specified
     *             array
     * @see java.lang.reflect.Array#get(Object, int)
     */
    @SuppressWarnings("unchecked")
    public static <T> T getElement(Object array, int index) throws ArrayIndexOutOfBoundsException {
        return (T) Array.get(array, index);
    }

    /**
     *  <code>componentType</code> ?  <code>length</code>.
     * 
     * <h3>:</h3>
     * 
     * <blockquote>
     * 
     * <pre class="code">
     * assertArrayEquals(new Integer[] {}, ArrayUtil.newArray(Integer.class, 0));
     * assertArrayEquals(new Integer[] { null, null, null }, ArrayUtil.newArray(Integer.class, 3));
     * </pre>
     * 
     * </blockquote>
     *
     * @param <T>
     *            the generic type
     * @param componentType
     *            the component type
     * @param length
     *            the length of the new array
     * @return  <code>componentType</code> null, {@link NullPointerException}<br>
     *          {@code length < 0} , {@link IllegalArgumentException}<br>
     * @see java.lang.reflect.Array#newInstance(Class, int)
     * @see java.lang.reflect.Array#newInstance(Class, int...)
     * @see "com.google.common.collect#newArray(Class, int)"
     * @since 1.6.1
     */
    @SuppressWarnings("unchecked")
    public static <T> T[] newArray(Class<T> componentType, int length) {
        Validate.notNull(componentType, "componentType can't be null!");
        Validate.isTrue(length >= 0, "length:[%s],must >=0", length);
        return (T[]) Array.newInstance(componentType, length);
    }

    /**
     * ?? {@link java.util.Iterator}.
     * <p>
     * ??,???with no copying<br>
     * ?, ClassCastException  ,Rats -- ,arrayList ?arrayList.iterator()
     * </p>
     * <p>
     * <b>:</b>{@link Arrays#asList(Object...)} list {@link Array}  ArrayList,
     * {@link java.util.AbstractList#add(int, Object)} ,<br>
     * listadd?, {@link java.lang.UnsupportedOperationException}
     * </p>
     * 
     * @param <T>
     *            the generic type
     * @param arrays
     *            ,? , 
     * @return if (null == arrays) return null;<br>
     *         ?arrays?Object[], {@link Arrays#asList(Object...)}?list,? {@link List#iterator()
     *         t}<br>
     *         ,? Object[],?, {@link Array#getLength(Object)}?, {@link Array#get(Object, int)} list
     * @see Arrays#asList(Object...)
     * @see Array#getLength(Object)
     * @see Array#get(Object, int)
     * @see List#iterator()
     */
    @SuppressWarnings({ "unchecked" })
    public static <T> Iterator<T> toIterator(Object arrays) {
        if (null == arrays) {
            return null;
        }
        List<T> list = null;
        try {
            // ??,???with no copying
            Object[] objArrays = (Object[]) arrays;
            list = (List<T>) toList(objArrays);
        } catch (ClassCastException e) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("arrays can not cast to Object[],maybe primitive type,values is:{},{}", arrays,
                        e.getMessage());
            }
            // Rats -- 
            int length = Array.getLength(arrays);
            list = new ArrayList<T>(length);
            for (int i = 0; i < length; ++i) {
                Object object = Array.get(arrays, i);
                list.add((T) object);
            }
        }
        return list.iterator();
    }

    /**
     * ? ({@link java.util.ArrayList ArrayList})list?add?.
     * <p>
     * ? :{@link java.util.Arrays#asList(Object...) Arrays#asList(Object...)}list, {@link java.util.Collection#add(Object)
     * Collection#add(Object)}<br>
     * , {@link ArrayList#ArrayList(java.util.Collection)} ???
     * </p>
     * 
     * @param <T>
     *            the generic type
     * @param arrays
     *            T
     * @return ? List(ArrayList)<br>
     *         if Validator.isNullOrEmpty(arrays), return null,else return {@code new ArrayList<T>(Arrays.asList(arrays));}
     * @see java.util.Arrays#asList(Object...)
     */
    public static <T> List<T> toList(T[] arrays) {
        if (Validator.isNullOrEmpty(arrays)) {
            return null;
        }
        //Arrays.asList(arrays) Arrays
        //ArraysArrayListAbstractListadd! strList.add("c");

        List<T> list = new ArrayList<T>(Arrays.asList(arrays));
        return list;
    }

    /**
     * ??Integer .
     * 
     * @param objects
     *            objects
     * @return Validator.isNotNullOrEmpty(objects)null<br>
     *         ??integer,?
     * @deprecated ?
     */
    //TODO ?
    @Deprecated
    public static Integer[] toIntegers(Object[] objects) {
        if (Validator.isNullOrEmpty(objects)) {
            return null;
        }

        int length = objects.length;
        Integer[] integers = new Integer[length];
        for (int i = 0; i < length; i++) {
            integers[i] = ObjectUtil.toInteger(objects[i]);
        }
        return integers;
    }

    /**
     *  ,???.<br>
     * equals ?,  ?equals.<br>
     * ? null
     * 
     * @param <T>
     *            the generic type
     * @param arrays
     *            
     * @param value
     *            
     * @return  Validator.isNotNullOrEmpty(arrays) false <br>
     *         ?arrays {@link ObjectUtil#equals(Object, Object, boolean)} ,truetrue<br>
     * @see ObjectUtil#equals(Object, Object, boolean)
     */
    public static <T> boolean isContain(T[] arrays, T value) {
        if (Validator.isNullOrEmpty(arrays)) {
            return false;
        }

        for (T arr : arrays) {
            if (ObjectUtil.equals(arr, value, true)) {
                return true;
            }
        }
        return false;
    }

    /**
     *   {@link ToStringConfig} ? .
     * 
     * 
     * <pre>
     * Example 1:
     * ArrayUtil.toString(new ToStringConfig(),"a","b")---->"a,b"
     * 
     * Example 2:
     * ToStringConfig toStringConfig=new ToStringConfig(",");
     * toStringConfig.setIsJoinNullOrEmpty(false);
     * ArrayUtil.toString(new ToStringConfig(),"a","b",null)---->"a,b"
     * </pre>
     *
     * @param <T>
     *            the generic type
     * @param toStringConfig
     *            the join string entity
     * @param arrays
     *            , Integer []arrays,? int []arrays //TODO
     * @return <ul>
     *         <li> arrays null Empty ,null</li>
     *         <li>?, {@link ToStringConfig#getConnector()}</li>
     *         </ul>
     */
    public static <T> String toString(ToStringConfig toStringConfig, T... arrays) {
        if (Validator.isNullOrEmpty(arrays)) {
            return null;
        }

        if (Validator.isNullOrEmpty(toStringConfig)) {
            toStringConfig = new ToStringConfig();
        }

        String connector = toStringConfig.getConnector();

        StringBuilder sb = new StringBuilder();
        for (int i = 0, j = arrays.length; i < j; ++i) {
            T t = arrays[i];

            //null  empty??
            if (Validator.isNullOrEmpty(t)) {
                if (!toStringConfig.getIsJoinNullOrEmpty()) {
                    continue;
                }
            }
            sb.append(t);
            if (Validator.isNotNullOrEmpty(connector)) {
                sb.append(connector);
            }
        }

        //???nullempty?????
        String returnValue = sb.toString();

        if (Validator.isNotNullOrEmpty(connector)) {
            if (returnValue.endsWith(connector)) {
                //?
                return StringUtil.substringWithoutLast(returnValue, connector.length());
            }
        }

        return returnValue;
    }

    /**
     * array .
     * 
     * <pre>
     * 
     * Example 1:
     * if Integer[] array = { 1, 1, 1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 8 };
     * 
     * will return 
     * 
     * {@code
     *      {
     *         "1":         [
     *             1,
     *             1,
     *             1
     *         ],
     *         "2":         [
     *             2,
     *             2
     *         ],
     *         "3": [3],
     *         "4": [4],
     *         "5":         [
     *             5,
     *             5
     *         ],
     *         "6": [6],
     *         "7": [7],
     *         "8":         [
     *             8,
     *             8
     *         ]
     *     }
     * }
     * </pre>
     *
     * @param <T>
     *            the generic type
     * @param array
     *            the array
     * @return the map< t, list< t>>
     * @since 1.0.8
     */
    public static <T> Map<T, List<T>> group(T[] array) {
        if (null == array) {
            return null;
        }
        //  ??? HashMap TreeMap
        Map<T, List<T>> map = new WeakHashMap<T, List<T>>(array.length);
        for (T t : array) {
            List<T> valueList = map.get(t);
            if (null == valueList) {
                valueList = new ArrayList<T>();
            }
            valueList.add(t);
            map.put(t, valueList);
        }
        return map;
    }

    /**
     * Group .
     *
     * @param <O>
     *            the generic type
     * @param <T>
     *            the generic type
     * @param objectArray
     *            
     * @param propertyName
     *            ????
     * @return the map< t, list< o>>
     * @see com.baozun.nebulaplus.bean.PropertyUtil#getProperty(Object, String)
     * @see com.baozun.nebulaplus.util.CollectionsUtil#group(java.util.Collection, String)
     * @since 1.0.8
     */
    public static <O, T> Map<T, List<O>> group(O[] objectArray, String propertyName) {
        if (null == objectArray) {
            return null;
        }

        if (Validator.isNullOrEmpty(propertyName)) {
            throw new NullPointerException("the propertyName is null or empty!");
        }
        //  ??? HashMap TreeMap
        Map<T, List<O>> map = new LinkedHashMap<T, List<O>>(objectArray.length);
        for (O o : objectArray) {
            T t = PropertyUtil.getProperty(o, propertyName);
            List<O> valueList = map.get(t);
            if (null == valueList) {
                valueList = new ArrayList<O>();
            }
            valueList.add(o);
            map.put(t, valueList);
        }
        return map;
    }
}