JAVA 陣列常用方法
阿新 • • 發佈:2019-01-23
//靜態初始化
int array[] = { 1, 2, 3, 4 };
//動態初始化
int array[] = new int[3];
//陣列長度
int length = array.length;
//獲取二維中第一維的長度
int length2 = array[0].length;
//遍歷
int[] array = new int[] { 1, 2, 3 };
for (int i : array) {
System.out.println(i);
}
//排序
int[] array = { 3, 2, 1, 4, 5 };
Arrays.sort(array);
//輸出
int[] array = { 1, 2, 3 };
System.out.println(Arrays.toString(array));
//陣列轉list
String[] array = { "a", "b", "c", "d", "e" };
List<String> list = new ArrayList<String>(Arrays.asList(array));
//陣列轉set
String[] array = { "a", "b", "c", "d", "e" };
Set<String> set = new HashSet<String>(Arrays.asList(array));
//list轉陣列
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
String[] array = new String[list.size()];
list.toArray(array);
for (String s : array)
System.out.println(s);
//陣列是否包含某值
String[] array = { "a", "b", "c", "d", "e" };
boolean b = Arrays.asList(array).contains("a");
System.out.println(b);
//數組合並
int[] array = org.apache.commons.lang.ArrayUtils.addAll(array1, array2);
//反轉
org.apache.commons.lang.ArrayUtils.reverse(array);
//移除
int array[] = { 1, 2, 3, 4 };
//動態初始化
int array[] = new int[3];
//陣列長度
int length = array.length;
//獲取二維中第一維的長度
int length2 = array[0].length;
//遍歷
int[] array = new int[] { 1, 2, 3 };
for (int i : array) {
System.out.println(i);
}
//排序
int[] array = { 3, 2, 1, 4, 5 };
Arrays.sort(array);
//輸出
int[] array = { 1, 2, 3 };
System.out.println(Arrays.toString(array));
//陣列轉list
String[] array = { "a", "b", "c", "d", "e" };
List<String> list = new ArrayList<String>(Arrays.asList(array));
//陣列轉set
String[] array = { "a", "b", "c", "d", "e" };
Set<String> set = new HashSet<String>(Arrays.asList(array));
//list轉陣列
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
String[] array = new String[list.size()];
list.toArray(array);
for (String s : array)
System.out.println(s);
//陣列是否包含某值
String[] array = { "a", "b", "c", "d", "e" };
boolean b = Arrays.asList(array).contains("a");
System.out.println(b);
//數組合並
int[] array = org.apache.commons.lang.ArrayUtils.addAll(array1, array2);
//反轉
org.apache.commons.lang.ArrayUtils.reverse(array);
//移除
int[] removed = org.apache.commons.lang.ArrayUtils.removeElement(array, 3);
【原創】原創文章,更多關注敬請關注微信公眾號。