数组
声明数组变量
下面是声明数组变量的语法:
dataType[] arrayRefVar; // 首选的方法
或
dataType arrayRefVar[]; // 效果相同,但不是首选方法
创建数组
数组变量的声明,和创建数组可以用一条语句完成,如下所示:
dataType[] arrayRefVar = new dataType[arraySize];
另外,你还可以使用如下的方式创建数组。
dataType[] arrayRefVar = {value0, value1, …, valuek};
数组的元素是通过索引访问的。数组索引从0开始,所以索引值从0到arrayRefVar.length-1。
数组作为函数的参数
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
数组作为函数的返回值
public static int[] reverse(int[] list) {
int[] result = new int[list.length];
for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
result[j] = list[i];
}
return result;
}
Arrays 类
java.util.Arrays类能方便地操作数组,它提供的所有方法都是静态的。具有以下功能:
给数组赋值:通过fill方法。
对数组排序:通过sort方法,按升序。
比较数组:通过equals方法比较数组中元素值是否相等。
查找数组元素:通过binarySearch方法能对排序好的数组进行二分查找法操作。
示例代码:
package Test;
public class Test {
/*
* 创建数组两种方法
*/
public static void customInit() {
// 实例方法一 (首选的方法)
double[] myList;
// 实例方法二 (效果相同,但不是首选方法)
double myList1[];
// 创建数组方法一
// dataType[] arrayRefVar = new dataType[arraySize];
// 创建数组方法二
// dataType[] arrayRefVar = {value0, value1, ..., valuek};
}
/*
* 计算所有元素的总和
*/
public static void creatList1() {
int size = 3;
int[] myList = new int[size];
myList[0] = 1;
myList[1] = 2;
myList[2] = 3;
int total = 0;
for (int i = 0; i < size ; i++) {
total += myList[i];
}
System.out.println("total总和:" + total);
}
/*
* 打印所有数组元素
*/
public static void createList2() {
int[] myList = {10,20,30};
for (int i = 0; i < myList.length; i++) {
System.out.println(i + "---" + myList[i] );
}
// 查找最大元素
int max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
/*
* foreach循环
*/
public static void foreachMethod() {
int[] ages = {11,22,33,44};
for (int i : ages) {
System.out.println(i);
}
}
/*
* 数组作为参数
*/
public static void printArraye(double[] array) {
for (double index : array) {
System.out.println(" 打印数组 :" + index);
}
}
/*
* 数组的创建和实例化
*/
public static void main(String[] args) {
Test test = new Test();
test.creatList1();
test.createList2();
test.foreachMethod();
double[] array = {100,200,300};
test.printArraye(array);
}
}
Demo地址:Demo10_数组
新浪微博:Hanrovey
163邮箱 : Hanrovey@163.com