zoukankan      html  css  js  c++  java
  • Java语言基础——数组那点事儿

        数组的声明和实例化,初始化方式

     1 int[] a = {1,2,3,4};
    2 int a[] = {1,2,3,4};//不会报错,不推荐这样写
    3 int[] a = new int[4];//4为数组的长度,数组的长度一旦确定就不能改变
    4 a = {1,2,3,4}//错误
    5 a[0]=1;
    6 a[1]=2;
    7 a[2]=3;
    8 a[3]=4;
    9 int[] a = new int[]{1,2,3,4};
    10 int[] b = new int[5]{1,2,3,4,5}; //错误
    11 String[] ss = {"张三","李四","往五"};


        数组的默认初始化(如果不赋值,则有默认值)

        各个数组的默认值如下

    byte,short,int,long : 0
    float,double : 0.0f, 0.0
    char: '\u0000' //不可见字符
    boolean : false
    对象 : null

        数组的访问和下标越界

    数组的下标(index)是从0开始
    例:

    1 public static void main(String[] args) {
    2 int[] a ; //数组的声明
    3 a = new int[2];
    4 a[0] = 10;//数组中的元素就是变量
    5 a[1] = 20;
    6 a[2] = 30;//错误,但是没有红线,运行会错,错误原因数组下标越界
    7 }


        数组遍历

        //数组的遍历赋值
      

    1       int[] a = new int[5];
    2 for(int i=0; i<a.length; i++){ //a.length : 数组的长度属性
    3 a[i] = i;
    4 }


        数组之间的拷贝System.arraycopy()和直接赋值的区别
         赋值a=b: 复制地址和值
        缺点:相互会影响

        例1:

     1 public class TestArray2 {
    2 public static void main(String[] args) {
    3 int[] a = {1,2,3,4,5};
    4 int[] b = {6,7,8,9,0};
    5 a = b; //b的地址赋值给a,b的地址就等于a的地址,所以他们指向的数组对象是同一个
    6 //如果需要复制,则需要用System.arraycopy(src, srcPos, dest, destPos, length)
    7
    8 a[0] = 100; //改变a[0]的值
    9 System.out.println("b[0]为" + b[0]); //在这里b[0]由于指向的是a[0]的数组对象,所以b[0]输出的值也是100
    10 }
    11
    12 }



        打印结果:b[0]为100

        如果需要复制且不影响原来的数组,则用
        System.arraycopy(src, srcPos, dest, destPos, length)
        src:从哪个数组里面拷,既源数组
        srcPos:从源数组中的第几个位置开始拷
        dest:目标数组
        destPos:从目标数组第几个位置开始拷贝
        length:要拷多长
        例2:
      

     1   public class TestArraycopy {
    2 /**
    3 * 打印方法
    4 * @param cs
    5 */
    6 public static void print(char[] cs){
    7 for(int i=0; i<cs.length; i++){
    8 System.out.print(cs[i] + " ");
    9 }
    10 }
    11
    12 public static void main(String[] args) {
    13 char[] cs = {'A','B','C','D','E'};
    14 char[] cs2 = {'0','0','0','0','0','0','0','0','0'};
    15 //cs2 = cs.clone();
    16 System.arraycopy(cs, 0, cs2, 0, 4);
    17 //从cs的第0个元素开始,到cs2的第0个元素开始,拷4个
    18 print(cs2);
    19
    20 }
    21
    22 }


        输出结果:A B C D 0 0 0 0 0

  • 相关阅读:
    VisualSVN-Server windows 版安装时报错 "Service 'VisualSVN Server' failed to start. Please check VisualSVN Server log in Event Viewer for more details."
    Pytest 单元测试框架之初始化和清除环境
    Pytest 单元测试框架入门
    Python(email 邮件收发)
    Python(minidom 模块)
    Python(csv 模块)
    禅道简介
    2020年最好的WooCommerce主题
    Shopify网上开店教程(2020版)
    WooCommerce VS Magento 2020:哪个跨境电商自建站软件更好?
  • 原文地址:https://www.cnblogs.com/hqr9313/p/2438265.html
Copyright © 2011-2022 走看看