8.3数组常见操作问题:
数组第二种方式:
元素类型[] 数组名 = new 元素类型 [] {元素,元素,};
8.4数组常见操作:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// 打印所有数组元素
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// 计算所有元素的总和
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// 查找最大元素
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
For-Each循环:
特点: 在不使用角标的情况下打印全部数组
for(type element: array)
{
System.out.println(element);
}
实例:
class Opration
{
public static void main(String[] args)
{
double[] myList = {1,3,3,4,5,6,7};
//打印所有数组元素
for(double element:myList)
{
System.out.println(element);
}
System.out.println("Hello World!");
}
}
数组作为函数的参数:
public static void printArray(double[] array)
{
for(int i = 0; i < array.length; i++)
{
System.out.println(array[i] + " ");
}
}
数组作为返回值:
class Opration
{
public static void main(String[] args)
{
double[] myList = {1,3,3,4,5,6,7};
//打印所有数组元素
/*for(double element:myList)
{
System.out.println(element);
}*/
printArray(myList);
System.out.println("Hello World!");
}
public static double[] printArray(double[] array)
{
/*for(int i = 0; i < array.length; i++)
{
System.out.println(array[i] + " ");
}*/
double[] result = new double[array.length];
for(int i = 0, j = result.length - 1; i < array.length; i++, j--)
{
result[j] = array[i];
}
return result;
}
}
多维数组:
多维数组可以看成是数组的数组,比如二维数组就是一个特殊的一位数组,其中一个元素都是一个一位数组例如
String str[ ][ ] = new String[3][4];
多为数组的动态初始化(以二维数组为例)
1.直接为每一维分配空间,格式如下
type[ ] [ ] typeName = new type[typeLength1][typeLength2];
type 可以为基本数据类型和复合数据类型,arraylength1 和 arraylength2 必须为正整数,arraylength1 为行数,arraylength2 为列数。
2. 从最高维开始,分别为每一维分配空间,例如:
String s[][] = new String[2][];
s[0] = new String[2];
s[1] = new String[3];
s[0][0] = new String("Good");
s[0][1] = new String("Luck");
s[1][0] = new String("to");
s[1][1] = new String("you");
s[1][2] = new String("!");
解析:
s[0]=new String[2] 和 s[1]=new String[3] 是为最高维分配引用空间,也就是为最高维限制其能保存数据的最长的长度,然后再为其每个数组元素单独分配空 间 s0=new String("Good") 等操作。
多维数组的引用(以二维数组为例)
对二维数组中的每个元素,引用方式为 arrayName[index1][index2],例如:
num[1][0];
Arrays 类
java.util.Arrays 类能方便地操作数组,它提供的所有方法都是静态的
具体功能如下:
给数组赋值:通过 fill 方法。
对数组排序:通过 sort 方法,按升序。
比较数组:通过 equals 方法比较数组中元素值是否相等。
查找数组元素:通过 binarySearch 方法能对排序好的数组进行二分查找法操作