数组

格式1:

type[] 变量名 = new type[数组中元素的个数];

格式2:

type变量名[] = new type[数组中元素的个数];

格式3:

type[] 变量名 = new type[]{逗号分隔的初始化值};

数组的元素是通过索引访问的。数组索引从 0 开始,所以索引值从 0 到 arrayRefVar.length-1。

java中的每个数组都有一个名为length的属性,表示数组的长度。

Arrays 类

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

具有以下功能:

  • 给数组赋值:通过 fill 方法。
  • 对数组排序:通过 sort 方法,按升序。
  • 比较数组:通过 equals 方法比较数组中元素值是否相等。
  • public class test {
        public static void main(String[] args) {
            
            /*
             * 一维数组
             * */
            String[] s=new String[5];
            s[0]="I";
            s[1]="love";
            s[2]="you";
            s[3]="mother";
            s[4]="feng";
            for(int i=0;i<s.length;i++){
                System.out.println(s[i]);
            }
            //triangle();
            ss();
        }
        
        /*
         * 二维数组
         * */
        
        public static void triangle(){
            String[][] s=new String[4][4];
            s[0][0]="I";
            s[1][1]="love";
            s[2][2]="you";
            s[3][3]="father";
                    
            for(int i =0;i<4;i++ ){
                for(int j=0;j<4;j++){
                    System.out.println(s[i][j]);
                }
                System.out.println("");
            }
            /*
             * 通过arrays类的方法,控制数组
             * 
             * */
            
        
            
        }
        public static void ss(){
            int[] a=new int[]{1,2,3,4};
            int[] b=new int[]{1,2,3,4};
            String s=Arrays.toString(a);//转换为string数组
            System.out.println(s);
            boolean f=Arrays.equals(a, b);//比较两个数组是否相等
            System.out.println(f);
            int[] ss=new int[]{3,4,5,6,72,3,1};
            Arrays.sort(ss);//进行升序排序
            System.out.println(Arrays.toString(ss));
        }
    }

     

posted @ 2017-05-16 21:39  呵呵呵学习  阅读(88)  评论(0)    收藏  举报