- 数组常用的遍历方式:
- for vs foreach
先定义一个数组
int[] array = {1, 2, 5, 6, 9, 3, 4};
for循环遍历数组
// for循环
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
while循环遍历数组
int i = 0;
while (i < array.length) {
System.out.println(array[i]);
i++;
}
do…while…循环遍历数组
int i = 0;
do {
System.out.println(array[i]);
i++;
} while (i < array.length);
foreach循环:增强的for循环
- 语法糖
for (int i : array) {
System.out.println(i);
}
数组的排序算法
- 冒泡排序
public static void main(String[] args) {
int[] array = { 3, 4, 5, 2, 1, 9, 6, 8, 7, 0 };
//升序
for (int i = 0; i < array.length - 1; i++) {
for (int j = 0; j < array.length - i - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
for (int i : array) {
System.out.print(i + " ");
}
}
排序方式有很多种,这里只说最常用的。
实现数组的自动扩容
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] scores = new double[3];
for (int i = 0; i < 10; i++) {
// 如果索引越界
if (i > scores.length - 1) {
//创建新数组,容量+1
//第一种方式
/** double[] tempArray = new double[scores.length + 1];
//将原数组的元素存储到新数组
for (int j = 0; j < scores.length; j++) {
tempArray[j] = scores[j];
}
//将原数组的变量名指向新数组
scores = tempArray;*/
//第二种方式
scores = Arrays.copyOf(scores, scores.length + 1);
}
System.out.println("请输入第"+ (i + 1) +"个学生的成绩:");
scores[i] = input.nextDouble();
}
for (double score : scores) {
System.out.print(score + " ");
}
input.close();
}
Arrays工具类
- 常用方法:
- toString(需要格式化的数组):返回固定格式的字符串
- sort(需要排序的数组):没有返回值,直接在原数组上做排序。注意:基本数据类型数组使用快速排序算法,引用数据类型数组使用并> > 归排序算法。
- binarySearch(目标数组,要查找的值):查找指定值在数组中的下标。如果没找到,返回负数。注意:二分查找一定要先排序(升序)
- copyOf(原数组, 新长度):返回新数组,注意:如果新长度比原数组容量小,复制时会舍弃多余的元素。如果新长度比原数组容量大,复制时会补全默认值。
- fill(目标数组, 指定数值):使用指定数值填充整个数组。
- equals(数组1, 数组2):比较两个数组是否相等。
例:
int[] array = { 1, 6, 2, 8, 3, 4, 7, 5, 9, 0 };
// for (int i : array) {
// System.out.println(i);
// }
//[1, 6, 2, 8, 3, 4, 7, 5, 9, 0]
String str = Arrays.toString(array);
System.out.println(str);
// 0 1 2 3 4 5 6 7 8 9
Arrays.sort(array);
System.out.println(Arrays.toString(array));
//二分查找,折半查找
int result = Arrays.binarySearch(array, 8);
System.out.println(result);
int[] newArray = Arrays.copyOf(array, 20);
System.out.println(Arrays.toString(newArray));
Arrays.fill(array, 8);
System.out.println(Arrays.toString(array));
boolean result1 = Arrays.equals(array, newArray);
System.out.println(result1);
Arrays扩展方法-流式编程
例:
double[] scores = { 33, 44, 55, 66, 77, 88, 99 };
//遍历
Arrays.stream(scores).forEach(x -> {
x+=10;
System.out.println(x);
});
System.out.println("================");
//筛选
Arrays.stream(scores)
.filter(x -> x >= 60)
.forEach(x -> System.out.println(x));
System.out.println("================");
//统计
long count = Arrays.stream(scores)
.filter(x -> x >= 60)
.count();
System.out.println(count);
//Arrays.stream(scores).sorted(Comparator.com).forEach(x -> System.out.println(x));