Java教程

Java笔记总结(十)---数组扩容和数据缩减

本文主要是介绍Java笔记总结(十)---数组扩容和数据缩减,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

数组扩容:

        int arr1[] = {1,2,3};
        int arr2[] = new int[arr1.length+1];
        for (int i = 0; i < arr2.length-1; i++) {
            arr2[i]=arr1[i];
            arr2[arr2.length-1]= 4;
        }
        System.out.println(Arrays.toString(arr2));

输出结果:
[1, 2, 3, 4]

数组缩减:

        int[] arr1 = {1, 2, 3, 4, 5};
        for (int i = 0; i <= arr1.length; i++) {
            if (arr1.length - i==0){
                System.out.println("不能再进行缩减");
                break;
            }
            int arr2[] = new int[arr1.length - i];
            for (int j = 0; j <= arr2.length-1; j++) {
                arr2[j] = arr1[j];
            }
            System.out.println(Arrays.toString(arr2));
        }

输出结果:
[1, 2, 3, 4, 5]
[1, 2, 3, 4]
[1, 2, 3]
[1, 2]
[1]
不能再进行缩减

这篇关于Java笔记总结(十)---数组扩容和数据缩减的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!