编程语言
首页 > 编程语言> > java考前复习之数组

java考前复习之数组

作者:互联网

声明数组变量

dataType[] arrayName;   // 首选的方法
 
dataType arrayName[];  // 效果相同,但不是首选方法

注意: 建议使用 dataType[] arrayName 的声明风格声明数组变量。 是因为dataType arrayName[] 风格是来自 C/C++ 语言 ,在Java中采用是为了让 C/C++ 程序员能够快速理解java语言。(大概是这个原因)

实例

下面是这两种语法的代码示例:

            int Name[];
	        Name=new int[100];
	        int []Name1;
	        Name1=new int[100];
            或
            int Name[]=new int[100];
            int []Name1=new int[100];

处理数组

 数组的元素类型和数组的大小都是确定的,所以当处理数组元素时候,我们通常使用基本for循环或者 加强型for 循环。


public class test {
	  public static void main(String args[]) {
		      int[] List = {1, 2, 3, 5};
		 
		      // 打印所有元素
		      for (int i = 0; i < List.length; i++) {//基本for循环
		         System.out.println(List[i] + " ");
		      }
		      // 计算元素总和
		      int  sum = 0;
		      for (int i = 0; i < List.length; i++) {
		         sum += List[i];
		      }
		      System.out.println("sum is " + total);
		      // 求最大元素
		      double max = List[0];
		      for (int i = 1; i < List.length; i++) {
		         if (List[i] > max) max = List[i];
		      }//求最大元素
		      System.out.println("Max is " + max);
		      for (int a:List) {//加强型for循环
			         System.out.println(a);
			      }
		   }
}

 注意:对于加强型for循环其中a,可以为任意名;而a前面的类型由List的类型决定;

其格式如下:

for(type reName: array)
{
    System.out.println(reName);
}

数组作为函数的参数

如下两种方法,和数组声明一样首选第一种方法


public class test {
	  public static void Print(String []args) {
		  for (int i = 0; i < args.length; i++) {
			    System.out.print(args[i] + " ");
			  }
		    
		   }
	  public static void Print1(String args[]) {
		  for (int i = 0; i < args.length; i++) {
			    System.out.print(args[i] + " ");
			  }
	   }
}

多维数组 :

     略。

Arrays 类

java.util.Arrays 类能方便地操作数组,它提供的所有方法都是静态的。

具有以下功能:

序号方法和说明
1public static int binarySearch(Object[] a, Object key)
用二分查找算法在给定数组中搜索给定值的对象(Byte,Int,double等)。数组在调用前必须排序好的。如果查找值包含在数组中,则返回搜索键的索引;否则返回 (-(插入点) - 1)。
2public static boolean equals(long[] a, long[] a2)
如果两个指定的 long 型数组彼此相等,则返回 true。如果两个数组包含相同数量的元素,并且两个数组中的所有相应元素对都是相等的,则认为这两个数组是相等的。换句话说,如果两个数组以相同顺序包含相同的元素,则两个数组是相等的。同样的方法适用于所有的其他基本数据类型(Byte,short,Int等)。
3public static void fill(int[] a, int val)
将指定的 int 值分配给指定 int 型数组指定范围中的每个元素。同样的方法适用于所有的其他基本数据类型(Byte,short,Int等)。
4public static void sort(Object[] a)
对指定对象数组根据其元素的自然顺序进行升序排列。同样的方法适用于所有的其他基本数据类型(Byte,short,Int等)。

标签:java,复习,考前,int,元素,List,System,static,数组
来源: https://blog.csdn.net/qq_51856496/article/details/121451326