Java数组的基本操作方法介绍
- java语言
- 关注:2.08W次
数组是具有相同数据类型的一组数据的集合,Java支持多为数组,一维数组的每个基本单元都是基本数据类型的数据,二维数组就是每个基本单元是一维数组的一维数组,以此类推,n维数组的每个基本单元都是n-1为数组的n-1维数组。下面以一维数组为例说明Java数组的用法。
1、数组声明
数组声明有如下两种形式(方括号的位置不同):
int arr[];int[] arr2;
2、数组初始化
数组初始化也有两种形式,如下(使用new或不使用new):
int arr[] = new int[]{1, 3, 5, 7, 9};int[] arr2 = {2, 4, 6, 8, 10};
3、遍历数组
遍历数组可用for/foreach,如下:
public static void main(String[] args) { int arr[] = new int[]{1, 3, 5, 7 ,9}; int[] arr2 = {2, 4, 6, 8, 10}; for (int i = 0; i < th; ++i) { t(arr[i] + "t"); // 1 3 5 7 9 } for (int x: arr2) { t(x + "t"); // 2 4 6 8 10 } }
4、()填充数组
使用Arrays类的静态方法,需要import包ys,定义了许多重载方法。
void fill(int[] a, int val)全部填充 void fill(int[] a, int fromIndex, int toIndex, int val)填充指定索引的元素 int[] arr3 = new int[5]; for (int x: arr3) { t(x + "t"); // 0 0 0 0 0 全部初始化为0 } tln(); (arr3, 10); for (int x: arr3) { t(x + "t"); // 10 10 10 10 10 全部填充为10 } tln(); (arr3, 1, 3, 8); for (int x: arr3) { t(x + "t"); // 10 8 8 10 10 填充指定索引 } tln();
5、()对数组排序
void sort(int[] a)全部排序 void sort(int[] a, int fromIndex, int toIndex)排序指定索引的'元素 int[] arr4 = {3, 7, 2, 1, 9}; (arr4); for (int x: arr4) { t(x + "t"); // 1 2 3 7 9 } tln(); int[] arr5 = {3, 7, 2, 1, 9}; (arr5, 1, 3); for (int x: arr5) { t(x + "t"); // 3 2 7 1 9 } tln();
6、Of()复制数组
int[] copyOf(int[] original, int newLength)复制数组,指定新数组长度 int[] copyOfRange(int[] original, int from, int to)复制数组,指定所复制的原数组的索引 int[] arr6 = {1, 2, 3, 4, 5}; int[] arr7 = Of(arr6, 5); // 1 2 3 4 5 int[] arr8 = OfRange(arr6, 1, 3); // 2 3 for (int x: arr7) { t(x + "t"); } tln(); for (int x: arr8) { t(x + "t"); } tln();
7、检查数组中是否包含某一个值
String[] stringArray = { "a", "b", "c", "d", "e" };boolean b = st(stringArray)ains("a");tln(b);// true
先使用st()将Array转换成List
8、连接两个数组
int[] intArray = { 1, 2, 3, 4, 5 };int[] intArray2 = { 6, 7, 8, 9, 10 };// Apache Commons Lang libraryint[] combinedIntArray = ll(intArray, intArray2);
ArrayUtils是Apache提供的数组处理类库,其addAll方法可以很方便地将两个数组连接成一个数组。
9、数组翻转
int[] intArray = { 1, 2, 3, 4, 5 };rse(intArray);tln(ring(intArray));//[5, 4, 3, 2, 1]
依然用到了万能的ArrayUtils。
10、从数组中移除一个元素
int[] intArray = { 1, 2, 3, 4, 5 };int[] removed = veElement(intArray, 3);//create a new tln(ring(removed));
- 文章版权属于文章作者所有,转载请注明 https://xuezhezhai.com/jsj/java/qrkox2.html