Java數組的十大方法


轉載自https://www.cnblogs.com/hglibin/p/9001876.html

Java數組的十大方法
以下是Java Array的前10種方法。他們是來自stackoverflow的投票最多的問題。

  • 0.聲明一個數組
123String[] aArray = new String[5];
String[] bArray = {"a","b","c", "d", "e"};
String[] cArray = new String[]{"a","b","c","d","e"};
  • 1.用Java打印數組
1234567int[] 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
1234String[] 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.檢查數組是否包含某個值
1234String[] stringArray = { "a", "b", "c", "d", "e" };
boolean b = Arrays.asList(stringArray).contains("a");
System.out.println(b);
// true
  • 4.連接兩個數組
1234int[] intArray = { 1, 2, 3, 4, 5 };
int[] intArray2 = { 6, 7, 8, 9, 10 };
// Apache Commons Lang library
int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);
  • 5.內聯聲明一個數組
1method(new String[]{"a", "b", "c", "d", "e"});
  • 6.將提供的數組的元素連接成單個字符串
12345// 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.將ArrayList包含到數組中
123456String[] 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.將數組轉換為集合
123Set<String> set = new HashSet<String>(Arrays.asList(stringArray));
System.out.println(set);
//[d, e, b, c, a]
  • 9.反轉一個數組
1234int[] intArray = { 1, 2, 3, 4, 5 };
ArrayUtils.reverse(intArray);
System.out.println(Arrays.toString(intArray));
//[5, 4, 3, 2, 1]
  • 10.刪除數組的元素
123int[] intArray = { 1, 2, 3, 4, 5 };
int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array
System.out.println(Arrays.toString(removed));
  • 再多一個 - 將int轉換為字節數組
1234byte[] bytes = ByteBuffer.allocate(4).putInt(8).array();
for (byte t : bytes) {
   System.out.format("0x%x ", t);
}

轉:https://www.programcreek.com/2013/09/top-10-methods-for-java-arrays/

作者:hglibin

出處:https://www.cnblogs.com/hglibin/p/9001876.html

感謝您的閱讀,本站使用「署名 4.0 國際」創作共享協議,如果您覺得閱讀本文對您有幫助,請點一下“推薦”按鈕。本文歡迎各位轉載,但是轉載文章之后必須在文章頁面中給出作者和原文連接


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM