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();
        }
      }
    }

  • 相关阅读:
    关于公司电脑修改host文件无法生效的问题
    Cannot access nexus-aliyun (http://maven.aliyun.com/nexus/content/groups/public) in offline mode and the artifact org.springframework
    DCL-单例模式的线程安全
    关于volatile
    关于CAS中的ABA问题存在的隐患
    无法获取 dpkg 前端锁 (/var/lib/dpkg/lock-frontend),是否有其他进程正占用它
    vue整合笔记
    vue9-axios、细节和杂项
    vue8-vuex、路径配置别名、promise
    vue07-路由 vue-router、keep-alive、tab-bar
  • 原文地址:https://www.cnblogs.com/xuyiqing/p/8206273.html
Copyright © 2011-2022 走看看