时间: 2020-08-25|53次围观|0 条评论

最近在写代码的过程中发现我们很多地方都会处理数组,有时只是模糊的记得有API可以调用,每次都查文档很是费事儿,适当的总结希望提高开发速度
这篇先介绍数组相关的操作,之后会介绍另外两个我认为同样常用的操作集合字符串相关的操作

一、申明数组

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

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

文章转载于:https://www.jianshu.com/p/bef8c1b93555

原著是一个有趣的人,若有侵权,请通知删除

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《Java数组最常用操作方法(Arrays类)
   

还没有人抢沙发呢~