Java-数组

Java 数组

  • Java语言中提供的数组是用来存储固定大小的同类型元素

  • 声明数组变量

      dataType[] arrayRefVar; //首选方法
      dataType arrayRefVar []; // 效果相同,但不是首选方法
      // 实例
      double[] myList;
    
  • 创建数组

      arrayRefVar = new dataType[arraySize];
      //数组变量的声明,和创建数组用一条语句完成
      dataType[] arrayRefVar = new dataType[arraySize];
      //实例
      double[] myList = new double[10];
    
  • 处理数组--基本循环或者foreach

      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.lenght; 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.lenght;i++) {
      			if (myList[i] > max) max = myList[i];
      		}
      		System.out.println("Max is" + max);
      	}
      }
    
  • foreach循环

      public class TestArray {
      	public static void main(String[] args) {
      		double[] myList = {1.9, 2.9, 3.4, 3.5};
      		//打印所有数组元素
      		for (double element: myList) {
      		System.out.println(element);
      		}
      	}
      }
    
  • 数组作为函数的参数

      public static void printArray(int[] array) {
      	for (int i = 0;i < array.lenght; i++) {
      		System.out.print(array[i] + " ");
      	}
      }
      //调用printArray方法
      printArray(new int[] {1,2,3});
    
  • 数组作为函数的返回值

      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;
      }
    
  • 多维数组

      type arrayName = new type[arrayLength1][arrayLength2];
      //实例
      int a[][] = new int[2][3];
    
  • Array 类
    java.util.Arrays类能方便地操作数组

  1. 给数组赋值:通过fill方法
  2. 对数组排序:通过sort方法
  3. 比较数组:通过equals方法比较数组中元素值是否相等
  4. 查找数组元素:通过binarySeach方法能对排序好的数组进行二分查找法操作
原文地址:https://www.cnblogs.com/yfife/p/7367510.html