超实用的Java数组技巧攻略

本文分享了关于Java数组最顶级的方法,帮助你解决工作流程问题,无论是运用在团队环境或是在私人项目中,你都可以直接拿来用!

 

超实用的Java数组技巧攻略

 

 

0.  声明一个数组(Declare an array)

 

String[] array01 = new String[5];
String[] array02 = new String[]{"a","b","c", "d", "e"};
String[] array03 = {"a","b","c","d","e"};

 1.  在Java中输出一个数组(Print an array in Java)

 

 

int[] intArray01 = {1,2,3,4,5,6};
String intArrayStr = Arrays.toString(intArray01);
		
System.out.println(intArray01);//[I@de6ced
System.out.println(intArrayStr);//[1, 2, 3, 4, 5, 6]

 

 

2. 从数组中创建数组列表(Create an ArrayList from an array)

 

String[] strArray01 = {"a","b","c", "d", "e"};
ArrayList<String> list = new ArrayList<String>(Arrays.asList(strArray01));
System.out.println(list);//[a, b, c, d, e]

 

 

3. 检查数组中是否包含特定值(Check if an array contains a certain value)

 

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

 

 

4. 连接两个数组( Concatenate two arrays)

 

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

 

 

5. 声明一个数组内链(Declare an array inline )

 

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

 

 

 

 

6. 将数组元素加入到一个独立的字符串中(Joins the elements of the provided array into a single String)

 

// Apache common lang
String str = StringUtils.join(new String[]{"a", "b", "c", "d", "e"});
System.out.println(str);//abcde

 

  

 

 

7. 将数组列表转换成一个数组 (Covnert an ArrayList to an array)

 

String[] strArray03 = {"a", "b", "c", "d", "e"};
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(strArray03));
String[] strArray04 = new String[arrayList.size()];
arrayList.toArray(strArray04);
for (String string : strArray04) {
System.out.print(string+" ");//a b c d e 
}

 

 

 

8. 将数组转换成一个集合(Convert an array to a set)

 

String[] strArray05 = {"a", "b", "c", "d", "e"}; 
Set<String> set = new HashSet<String>(Arrays.asList(strArray05));
System.out.println(set);//[d, e, b, c, a]

 

 9 反向数组(Reverse an array)

int[] intArray04 = {1,2,3,4,5,6};
ArrayUtils.reverse(intArray04);
System.out.println(Arrays.toString(intArray04));//[6, 5, 4, 3, 2, 1]

 

10.删除数组元素(Remove element of an array)

int[] intArray05 = { 1, 2, 3, 4, 5 };
int[] removed = ArrayUtils.removeElement(intArray05, 3);
System.out.println(ArrayUtils.toString(removed));//{1,2,4,5}

 

 

你可能感兴趣的:(java)