Java中Array的常用方法

itjhwd發表於2014-06-05

  0.建立/宣告一個陣列

String[] aArray = new String[5];
String[] bArray = {"a","b","c", "d", "e"};
String[] cArray = new String[]{"a","b","c","d","e"};

  1.Java中列印陣列

int[] intArray = { 1, 2, 3, 4, 5 };
String intArrayString = Arrays.toString(intArray);

// print directly will print reference value
System.out.println(intArray);
// [I@7150bd4d

System.out.println(intArrayString);
// [1, 2, 3, 4, 5]

  2.用陣列建立一個ArrayList

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]

  3,檢查陣列中是否包含特定的值

String[] stringArray = { "a", "b", "c", "d", "e" };
boolean b = Arrays.asList(stringArray).contains("a");
System.out.println(b);

  4.結合兩個陣列

int[] intArray = { 1, 2, 3, 4, 5 };
int[] intArray2 = { 6, 7, 8, 9, 10 };
// Apache Commons Lang library
int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);

  5.宣告一個陣列的方法

method(new String[]{"a", "b", "c", "d", "e"});

  6,加入所提供的陣列中的元素連線成一個字串

// containing the provided list of elements
// Apache common lang
String j = StringUtils.join(new String[] { "a", "b", "c" }, ", ");
System.out.println(j);
// a, b, c

  7. Array與List之間的轉換

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.陣列轉換成set

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, 2, 3, 4, 5 };
int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array
System.out.println(Arrays.toString(removed));

  最後一下int轉換成byte陣列

byte[] bytes = ByteBuffer.allocate(4).putInt(8).array();

for (byte t : bytes) {
System.out.format("0x%x ", t);
}

  英文原文:top-10-methods-for-java-arrays

相關文章