java数组8个常用方法

2020-03-28  本文已影响0人  周文冬

开发过程中,数组是常用数据类型之一,收集一下常用方法;
这篇先介绍数组相关的操作,之后会介绍另外两个我认为同样常用的操作集合和字符串相关的操作

一、申明数组

数组的申明十分简单也十分的基础,注意第三种申明方式,[ ]里面是不带数字的

String[] Array1 = new String[5];  
String[] Array2 = {"a","b","c", "d", "e"};  
String[] Array3 = new String[]{"a","b","c","d","e"};  

二、打印数组

直接打印数组链表我们会打印出对象的hash值,我们可以先调用Arrays.toString()方法,再打印数组消息

int[] intArray = { 1, 2, 3, 4, 5 };  
String intArrayString = Arrays.toString(intArray);  
// 直接打印,则会打印出引用对象的Hash值  
// [I@7150bd4d  
System.out.println(intArray);   
// [1, 2, 3, 4, 5]  
System.out.println(intArrayString);  

三、数组转换为集合

此方法同Collection.toArray() 一起,充当了基于数组的 API 与基于 collection 的 API 之间的桥梁。Arrays.asList(T...a)返回List<T>类型数据,同时可以将该集合当参数传入实例化具体的集合

String[] stringArray = { "a", "b", "c", "d", "e" };  
//转换为ArrayList<String>
ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(stringArray));  
System.out.println(arrayList);//输出[a, b, c, d, e]  
//转换为HashSet<String>
Set<String> set = new HashSet<String>(Arrays.asList(stringArray));  
System.out.println(set);//输出[d, e, b, c, a] 

四、ArrayList转换为数组

这里用的集合自带的Collection.toArray()方法

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);  

下面提供的一些功能是org.apache.commons.lang包提供的

五、合并两个数组

当然也可以用根据Array和Array2的length和来构建新的数组,再为新的数组赋值

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

六、数组的反转

不用包的话就倒序遍历数组为新数组赋值就行了

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

七、移除元素

这个功能自己单独实现也不难,只是移动数据总是麻烦的

int[] intArray = { 1, 2, 3, 4, 5 };  
int[] removed = ArrayUtils.removeElement(intArray, 3);//创建新的数组  
System.out.println(Arrays.toString(removed));  

八、获取数组元素

这个功能自己单独实现也不难,只是移动数据总是麻烦的

int[] intArray = { 1, 2, 3, 4, 5 };  
int b = intArray[0];
上一篇下一篇

猜你喜欢

热点阅读