java数组常用方法

以下总结了java数组常用的10个方法!

package com.dxc.collection;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by duanxiangchao on 2015/9/9.
 */
public class ArrayDemo {

    public static void main(String[] str){

        //  1. 数组的声明、初始化
        //定义时指定数组的大小(推荐)
        String [] aArray = new String[5];
        //定义时直接初始化
        String [] bArray = {"a","b","c","e","f"};
        String [] cArray = new String[]{"a","b","c","e","f"};

        //  2. 使用Arrays.toString(Collection)方法可以数组转变为String
        int [] intArray = new int[]{1,2,3,4,5};
        String intArrayStr = Arrays.toString(intArray);
        System.out.println(intArray.toString());
        System.out.println(intArrayStr);

        
        //  3. 判断数组是否包含某个值
        boolean contain = Arrays.asList(bArray).contains("a");
        System.out.println(contain);

        //  4. 用指定的字符串链接数组
        String join = StringUtils.join(new String[]{"a", "b", "c", "d", "e"}, ";");
        System.out.println(join);   //结果 a;b;c;e;f
        
        //  5. 合并两个数组
        int [] intArray1 = {1,2,3,4,5};
        int [] intArray2 = {6,7,8,9,10};
        //Apache commons lang 库
        int [] combinedArray = ArrayUtils.addAll(intArray1, intArray2);
        System.out.println(combinedArray);
        
        //  6. 数组的反转
        int [] arr = {1, 2, 3, 4, 5};
        ArrayUtils.reverse(arr);
        System.out.println(Arrays.toString(arr));
        
        //  7. 移除元素,会创建新的数组
        int [] moveArray = new int[]{1,2,3,4,5,6,7,8,9,10};
        int [] removeArray = ArrayUtils.remove(moveArray, 5);  //参数为 数组和索引
        System.out.println(Arrays.toString(removeArray));

        //  8. 根据数组创建ArrayList
        String [] array =  {"a","b","c","e","f"};
        ArrayList arrayList = new ArrayList(Arrays.asList(array));
        System.out.println(arrayList);

        //  9. 将ArrayList转换为数组
        Object [] objArray =  arrayList.toArray();
        System.out.println("ArrayList转数组:" + Arrays.toString(objArray));


        //  10. 将数组转化为Set
        Set set = new HashSet(Arrays.asList(bArray ));
        System.out.println("数组转化Set: " + set);
        
    }

}


你可能感兴趣的:(java基础核心)