java 數據結構(2) Array

一、概念

1.array無法判斷其中實際存有多少元素,length只是告訴我們array的容量。

二、參考關于 Java 數組的 12 個最佳方法
  1. 聲明一個數組
String[] aArray = new String[5];  
String[] bArray = {"a","b","c", "d", "e"};  
String[] cArray = new String[]{"a","b","c","d","e"};  
  1. 輸出一個數組
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]  
  1. 從一個數組創建數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]
  1. 檢查一個數組是否包含某個值
String[] stringArray = { "a", "b", "c", "d", "e" };  
boolean b = Arrays.asList(stringArray).contains("a");  
System.out.println(b);  
// true  
  1. 連接兩個數組
int[] intArray = { 1, 2, 3, 4, 5 };  
int[] intArray2 = { 6, 7, 8, 9, 10 };  
// Apache Commons Lang library  
int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);  
  1. 聲明一個內聯數組(Array inline)
method(new String[]{"a", "b", "c", "d", "e"});  
  1. 把提供的數組元素放入一個字符串
// 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
  1. 將一個數組列表轉換為數組
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);
  1. 將一個數組轉換為集(set)
Set<String> set = new HashSet<String>(Arrays.asList(stringArray));
System.out.println(set);
//[d, e, b, c, a]
  1. 逆向一個數組
int[] intArray = { 1, 2, 3, 4, 5 };  
ArrayUtils.reverse(intArray);  
System.out.println(Arrays.toString(intArray));  
//[5, 4, 3, 2, 1]  
  1. 移除數組中的元素
int[] intArray = { 1, 2, 3, 4, 5 };  
int[] removed = ArrayUtils.removeElement(intArray, 3);//create a new array  
System.out.println(Arrays.toString(removed));  
  1. 將整數轉換為字節數組
byte[] bytes = ByteBuffer.allocate(4).putInt(8).array();
for (byte t : bytes) {  
   System.out.format("0x%x ", t);  
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,779評論 18 399
  • Java經典問題算法大全 /*【程序1】 題目:古典問題:有一對兔子,從出生后第3個月起每個月都生一對兔子,小兔子...
    趙宇_阿特奇閱讀 1,916評論 0 2
  • 小編費力收集:給你想要的面試集合 1.C++或Java中的異常處理機制的簡單原理和應用。 當JAVA程序違反了JA...
    八爺君閱讀 4,674評論 1 114
  • 一、 1、請用Java寫一個冒泡排序方法 【參考答案】 public static void Bubble(int...
    獨云閱讀 1,421評論 0 6
  • 牛 牛跳崖,摔死了。 這句話就像是瘟疫一樣,傳遍了整個村子。 多么好的一頭牛。它曾經為家里立下過多少汗馬功勞!但是...
    牛賦閱讀 556評論 10 10