69

我已经搜索了一种在 Java 中调整数组大小的方法,但是我找不到在保留当前元素的同时调整数组大小的方法。

我找到了类似的示例代码int[] newImage = new int[newWidth];,但这会删除之前存储的元素。

我的代码基本上会这样做:每当添加新元素时,数组都会增大1。我认为这可以通过动态编程来完成,但我不确定如何实现它。

4

12 回答 12

113

您无法在 Java 中调整数组的大小。您需要:

  1. 创建一个所需大小的新数组,并将原始数组中的内容复制到新数组,使用java.lang.System.arraycopy(...);

  2. 使用java.util.ArrayList<T>该类,当您需要使数组更大时,它会为您执行此操作。它很好地封装了您在问题中描述的内容。

  3. 使用java.util.Arrays.copyOf(...)返回更大数组的方法,其中包含原始数组的内容。

于 2012-11-02T15:00:13.893 回答
31

不好,但有效:

    int[] a = {1, 2, 3};
    // make a one bigger
    a = Arrays.copyOf(a, a.length + 1);
    for (int i : a)
        System.out.println(i);

如前所述,使用ArrayList

于 2012-11-02T15:02:26.867 回答
24

这里有几种方法可以做到这一点。


方法一System.arraycopy()::

将指定源数组中的数组从指定位置开始复制到目标数组的指定位置。数组组件的子序列从 src 引用的源数组复制到 dest 引用的目标数组。复制的组件数量等于长度参数。源数组中位置 srcPos 到 srcPos+length-1 的分量分别复制到目标数组的位置 destPos 到 destPos+length-1。

Object[] originalArray = new Object[5];   
Object[] largerArray = new Object[10];
System.arraycopy(originalArray, 0, largerArray, 0, originalArray.length);

方法二Arrays.copyOf()::

复制指定的数组,截断或填充空值(如有必要),使副本具有指定的长度。对于在原始数组和副本中都有效的所有索引,这两个数组将包含相同的值。对于在副本中有效但在原始副本中无效的任何索引,副本将包含 null。当且仅当指定长度大于原始数组的长度时,此类索引才会存在。结果数组与原始数组的类完全相同。

Object[] originalArray = new Object[5];   
Object[] largerArray = Arrays.copyOf(originalArray, 10);

请注意,这种方法通常System.arraycopy() 在幕后使用。


方法 3: ArrayList:

List 接口的可调整大小的数组实现。实现所有可选列表操作,并允许所有元素,包括 null。除了实现 List 接口之外,该类还提供了一些方法来操作内部用于存储列表的数组的大小。(这个类大致相当于 Vector,只是它是不同步的。)

ArrayList 的功能类似于数组,除了当您添加的元素超过它可以包含的内容时它会自动扩展。它由 array 支持,并使用 Arrays.copyOf

ArrayList<Object> list = new ArrayList<>();

// This will add the element, resizing the ArrayList if necessary.
list.add(new Object());
于 2015-09-04T18:05:16.827 回答
5

您可以使用ArrayListwhich 为您完成这项工作。

于 2012-11-02T14:58:08.267 回答
4

无法更改数组大小。 但是您可以通过创建更大尺寸的 Array 将一个数组的元素复制到另一个数组中。

如果 Array 已满,建议创建双倍大小的 Array,如果 Array 已满一半,建议将 Array 减半

public class ResizingArrayStack1 {
    private String[] s;
    private int size = 0;
    private int index = 0;

    public void ResizingArrayStack1(int size) {
        this.size = size;
        s = new String[size];
    }


    public void push(String element) {
        if (index == s.length) {
            resize(2 * s.length);
        }
        s[index] = element;
        index++;
    }

    private void resize(int capacity) {
        String[] copy = new String[capacity];
        for (int i = 0; i < s.length; i++) {
            copy[i] = s[i];
            s = copy;
        }
    }

    public static void main(String[] args) {
        ResizingArrayStack1 rs = new ResizingArrayStack1();
        rs.push("a");
        rs.push("b");
        rs.push("c");
        rs.push("d");
    }
}
于 2017-10-15T19:59:42.667 回答
2

您可以使用 ArrayList 而不是数组。这样您就可以添加 n 个元素

 List<Integer> myVar = new ArrayList<Integer>();
于 2012-11-02T14:59:44.107 回答
2

标准类 java.util.ArrayList 是可调整大小的数组,随着新元素的添加而增长。

于 2012-11-02T14:59:52.473 回答
1

您无法调整数组的大小,但可以重新定义它以保留旧值或使用 java.util.List

以下是两个解决方案,但在运行下面的代码时发现了性能差异

Java 列表快 450 倍,但内存重 20 倍!

testAddByteToArray1 nanoAvg:970355051 memAvg:100000
testAddByteToList1 nanoAvg:1923106 memAvg:2026856
testAddByteToArray1 nanoAvg:919582271 memAvg:100000
testAddByteToList1 nanoAvg:1922660 memAvg:2026856
testAddByteToArray1 nanoAvg:917727475 memAvg:100000
testAddByteToList1 nanoAvg:1904896 memAvg:2026856
testAddByteToArray1 nanoAvg:918483397 memAvg:100000
testAddByteToList1 nanoAvg:1907243 memAvg:2026856
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static byte[] byteArray = new byte[0];
    public static List<Byte> byteList = new ArrayList<>();
    public static List<Double> nanoAvg = new ArrayList<>();
    public static List<Double> memAvg = new ArrayList<>();

    public static void addByteToArray1() {
        // >>> SOLUTION ONE <<<
        byte[] a = new byte[byteArray.length + 1];
        System.arraycopy(byteArray, 0, a, 0, byteArray.length);
        byteArray = a;
        //byteArray = Arrays.copyOf(byteArray, byteArray.length + 1); // the same as System.arraycopy()
    }

    public static void addByteToList1() {
        // >>> SOLUTION TWO <<<
        byteList.add(new Byte((byte) 0));
    }

    public static void testAddByteToList1() throws InterruptedException {
        System.gc();
        long m1 = getMemory();
        long n1 = System.nanoTime();
        for (int i = 0; i < 100000; i++) {
            addByteToList1();
        }
        long n2 = System.nanoTime();
        System.gc();
        long m2 = getMemory();
        byteList = new ArrayList<>();
        nanoAvg.add(new Double(n2 - n1));
        memAvg.add(new Double(m2 - m1));
    }

    public static void testAddByteToArray1() throws InterruptedException {
        System.gc();
        long m1 = getMemory();
        long n1 = System.nanoTime();
        for (int i = 0; i < 100000; i++) {
            addByteToArray1();
        }
        long n2 = System.nanoTime();
        System.gc();
        long m2 = getMemory();
        byteArray = new byte[0];
        nanoAvg.add(new Double(n2 - n1));
        memAvg.add(new Double(m2 - m1));
    }

    public static void resetMem() {
        nanoAvg = new ArrayList<>();
        memAvg = new ArrayList<>();
    }

    public static Double getAvg(List<Double> dl) {
        double max = Collections.max(dl);
        double min = Collections.min(dl);
        double avg = 0;
        boolean found = false;
        for (Double aDouble : dl) {
            if (aDouble < max && aDouble > min) {
                if (avg == 0) {
                    avg = aDouble;
                } else {
                    avg = (avg + aDouble) / 2d;
                }
                found = true;
            }
        }
        if (!found) {
            return getPopularElement(dl);
        }
        return avg;
    }

    public static double getPopularElement(List<Double> a) {
        int count = 1, tempCount;
        double popular = a.get(0);
        double temp = 0;
        for (int i = 0; i < (a.size() - 1); i++) {
            temp = a.get(i);
            tempCount = 0;
            for (int j = 1; j < a.size(); j++) {
                if (temp == a.get(j))
                    tempCount++;
            }
            if (tempCount > count) {
                popular = temp;
                count = tempCount;
            }
        }
        return popular;
    }

    public static void testCompare() throws InterruptedException {
        for (int j = 0; j < 4; j++) {
            for (int i = 0; i < 20; i++) {
                testAddByteToArray1();
            }
            System.out.println("testAddByteToArray1\tnanoAvg:" + getAvg(nanoAvg).longValue() + "\tmemAvg:" + getAvg(memAvg).longValue());
            resetMem();
            for (int i = 0; i < 20; i++) {
                testAddByteToList1();
            }
            System.out.println("testAddByteToList1\tnanoAvg:" + getAvg(nanoAvg).longValue() + "\t\tmemAvg:" + getAvg(memAvg).longValue());
            resetMem();
        }
    }

    private static long getMemory() {
        Runtime runtime = Runtime.getRuntime();
        return runtime.totalMemory() - runtime.freeMemory();
    }

    public static void main(String[] args) throws InterruptedException {
        testCompare();
    }
}
于 2017-02-10T00:13:06.970 回答
1

您可以在某个类中尝试以下解决方案:

int[] a = {10, 20, 30, 40, 50, 61};

// private visibility - or change it as needed
private void resizeArray(int newLength) {
    a = Arrays.copyOf(a, a.length + newLength);
    System.out.println("New length: " + a.length);
}
于 2018-07-05T13:22:09.497 回答
0

无法调整数组的大小。但是,可以通过将原始数组复制到新大小的数组并保留当前元素来更改数组的大小。还可以通过删除元素和调整大小来减小数组的大小。

import java.util.Arrays 
public class ResizingArray {

    public static void main(String[] args) {

        String[] stringArray = new String[2] //A string array with 2 strings 
        stringArray[0] = "string1";
        stringArray[1] = "string2";

        // increase size and add string to array by copying to a temporary array
        String[] tempStringArray = Arrays.copyOf(stringArray, stringArray.length + 1);
        // Add in the new string 
        tempStringArray[2] = "string3";
        // Copy temp array to original array
        stringArray = tempStringArray;

       // decrease size by removing certain string from array (string1 for example)
       for(int i = 0; i < stringArray.length; i++) {
           if(stringArray[i] == string1) {
               stringArray[i] = stringArray[stringArray.length - 1];
               // This replaces the string to be removed with the last string in the array
               // When the array is resized by -1, The last string is removed 
               // Which is why we copied the last string to the position of the string we wanted to remove
               String[] tempStringArray2 = Arrays.copyOf(arrayString, arrayString.length - 1);
                // Set the original array to the new array
               stringArray = tempStringArray2;
           }
       }
    }    
}
于 2016-07-29T23:21:11.980 回答
0

抱歉,但此时无法调整数组大小,并且可能永远不会。

所以我的建议是考虑找到一个解决方案,让您从流程开始就获得您需要的数组大小。这通常意味着您的代码需要更多时间(行)才能运行,但您会节省大量内存资源。

于 2018-10-03T20:20:22.830 回答
0

我们不能使用数组数据类型来做到这一点。而是使用一个可增长的数组,它是 Java 中的 arrayList。

于 2022-02-09T11:23:21.117 回答