zoukankan      html  css  js  c++  java
  • Java学习笔记3(数组)

    1.数组的定义:

    第一种:

    public class ArrayDemo{
      public static void main(String[] args){
      //定义数组
      int [] arr = new int[3];
      //数组中的元素默认值为0
      System.out.println(arr[0]);
      System.out.println(arr.length);
      }
    }

    这里的length是数组的长度

    第二种定义方法:

    public class ArrayDemo{
      public static void main(String[ ] args){
      //定义数组,注意new后边的中括号不能写数字
      int [ ] arr = new int[ ]{1,2,4,3,6,5};
      System.out.println(arr[4]);
      System.out.println(arr.length);
      }
    }

    第三种(最常用的):

    public class ArrayDemo{
      public static void main(String[ ] args){
      int [ ] arr = {1,2,4,3,6,5};
      System.out.println(arr[4]);
      System.out.println(arr.length);
      }
    }

    两种的结果相同,如下:

    2.数组的赋值:

    arr[1] = 3

    3.遍历

    public class ArrayDemo{
      public static void main(String[] args){
        int [] arr = {2,1,3,5,7,0,4};
        for(int i = 0 ; i < arr.length; i++){
        System.out.println(arr[i]);
        }
      }
    }

    结果:

    4.获取最大值(最小值原理相同):

    public class ArrayDemo{
      public static void main(String[] args){
        int [] arr = {5,-1,2,-4,6,0,8,3};
        int max = arr[0];
        for(int i = 1 ; i < arr.length; i++){
          if( max < arr[i]){
            max = arr[i];
          }
        }
        System.out.println(max);
      }
    }

    5.二维数组:

    定义:

    int  [][] arr = new int [3][4];

    int [][] arr = {{1,2},{3,4,5},{6,7,8,9}};

    内存方法:在堆中存三个一维数组,每个一维数组有四个位置,三个一维数组的首地址存入一个新的数组,这个新数组也有首地址,栈中的arr指向这个地址

    二维数组访问和一维数组类似

    遍历:

    public class ArrayDemo{
      public static void main(String[] args){
        int [][] arr = {{1,2,3},{4,5},{6,7,8,9},{0}};
        for(int i = 0 ; i < arr.length; i++){
          for(int j = 0 ; j<arr[i].length; j++){
            System.out.print(arr[i][j]);
          }
          System.out.println();
        }
      }
    }

  • 相关阅读:
    anconda + python 3.6安装(以前的anconda,anaconda和python版本对应关系)
    数学建模python matlab 编程(喷泉模拟)
    使用git checkout 指定git代码库上的指定分支
    aapt命令获取apk具体信息(包名、版本号号、版本号名称、兼容api级别、启动Activity等)
    toad for oracle中文显示乱码
    storm是怎样保证at least once语义的
    记使用WaitGroup时的一个错误
    Drupal 初次使用感受,兴许补充。
    Qt 5.5.0 Windows环境搭建
    有趣的Ruby-学习笔记3
  • 原文地址:https://www.cnblogs.com/xuyiqing/p/8206273.html
Copyright © 2011-2022 走看看