参考网上文章,总结了一下java数组使用技巧,如下:
package com.beijing.array; import java.nio.ByteBuffer; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang.ArrayUtils; /** * * @description java数组使用技巧 * @author liuchao * @createTime 2013年10月10日上午10:27:15 */ public class ArrayTest { public static void main(String[] args) { // 1.声明数组 /* * String[] a = new String[5]; String[] b = {"a","b","c","d","e"}; * String[] c = new String[]{"a","b","c","d","e"}; */ // 2.在java中输出一个数组 /* * int[] intArray = {1,2,3,4,5}; String intArrayString = * Arrays.toString(intArray); * * System.out.println(intArray);//[I@de6ced * System.out.println(intArrayString);//[1, 2, 3, 4, 5] */ // 3.从数组中创建列表 /* * String[] stringArray = {"a","b","c","d","e"}; ArrayList<String> * arrayList = new ArrayList<String>(Arrays.asList(stringArray)); * System.out.println(arrayList);//[a, b, c, d, e] */ // 4.检查数组中是否包含特定值 /* * String[] stringArray = {"a","b","c","d","e"}; boolean b = * Arrays.asList(stringArray).contains("a"); * System.out.println(b);//true */ // 5.连接连个数组 /* * int[] intArray = {1,2,3,4,5}; int[] intArray2 = {6,7,8,9,10}; * * //use apache commons lang library int[] combinedIntArray = * ArrayUtils.addAll(intArray, intArray2); for (int i = 0; i < * combinedIntArray.length; i++) { * System.out.print(combinedIntArray[i]+","); } * * //1,2,3,4,5,6,7,8,9,10, */ // 6.将数组元素加入到一个独立的字符串中(即用独立的字符串分割数组元素) /* * String str = StringUtils.join(new String[]{"a","b","c"}, ","); * System.out.println(str);//a,b,c */ //7.将数组列表转换成一个数组 /*String[] stringArray = { "a", "b", "c", "d", "e" }; ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray)); String[] stringArr = new String[arrayList.size()]; arrayList.toArray(stringArr); for(String s : stringArr){ System.out.println(s); }*/ //8.将数组转换成一个集合 /*String[] stringArray = { "a", "b", "c", "d", "e" }; Set<String> set = new HashSet<String>(Arrays.asList(stringArray)); System.out.println(set);//[d, e, b, c, a] */ //9.反向数组 /*int[] intArray = {1,2,3,4,5}; ArrayUtils.reverse(intArray); System.out.println(Arrays.toString(intArray));//[5, 4, 3, 2, 1] */ //10.删除数组元素 /*int[] intArray = {1,34,3,2,56,13,13,45,2}; int[] removed = ArrayUtils.removeElement(intArray, 2);//删除第一个匹配的元素 System.out.println(Arrays.toString(removed));*/ //11.把整数转换成字节数组 /*byte[] bytes = ByteBuffer.allocate(4).putInt(8).array(); for (byte t : bytes) { System.out.format("0x%x ", t);//0x0 0x0 0x0 0x8 }*/ //一个整数与0xFF进行&操作,得到该整数的二进制表示 /*ByteBuffer buffer = ByteBuffer.allocate(1024); //分配一定的空间,1024 int i = 90; buffer.putInt(i); byte[] array = buffer.array(); //获取该buffer的数组,这个数组是跟该buffer一一对应的 for(int j =0; j <4;j++){ System.out.println(Integer.toBinaryString(array[j] & 0xFF));//1011010 }*/ } }