在Java中如何调整数组大小并保留当前元素?

79

我一直在搜索Java中调整数组大小的方法,但无法找到在 保留当前元素 的情况下调整数组大小的方法。

例如,我发现类似于 int[] newImage = new int[newWidth]; 的代码,但这会删除之前存储的元素。

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


4
你正在寻找 ArrayList 吗? - jlordo
12个回答

123
你无法在Java中调整数组的大小。你需要做以下两种方法之一:
  1. 创建一个所需大小的新数组,并使用 java.lang.System.arraycopy(...); 将原始数组的内容复制到新数组中。

  2. 使用 java.util.ArrayList<T> 类,当你需要扩大数组时,它会自动为你完成这个操作。它很好地封装了你在问题描述中所描述的内容。

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


好的,我的ArrayList是一个名为“checker”的类类型,它存储不同的对象(int、string等)。我创建了一个新的“checker”类型的对象,分配了一些值,并将其添加到ArrayList中。现在Eclipse将进入调试模式,但控制台没有显示任何错误。你知道可能出了什么问题吗? - Mihai Bujanca
4
你应该将这个问题作为一个独立的问题来询问。 - Steve McLeod

35

虽不太美观,但能正常工作:

    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


4
值得注意的是,ArrayList为了避免在每次插入或删除时都要复制数组而增加了复杂性。 - Bernhard Barker

26

这里有几种方法可以实现它。


方法1:System.arraycopy()

从指定的源数组开始位置复制一个数组到目标数组的指定位置。 源数组中的子序列组件从 src 引用的源数组被复制到 dest 引用的目标数组中。 复制的组件数等于 length 参数。 源数组中位置 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 以使副本具有指定的长度。对于原始数组和副本中都有效的所有索引,两个数组将包含相同的值。对于仅在副本而非原始数组中有效的任何索引,副本将包含 null。当且仅当指定的长度大于原始数组的长度时,才会存在这样的索引。生成的数组与原始数组完全相同。

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

请注意,该方法通常使用System.arraycopy()在幕后
方法3: ArrayList:

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

ArrayList的功能类似于数组,当你添加的元素超过了它所能容纳的元素时,它会自动扩展。它是由一个数组支持,并且使用Arrays.copyOf

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

// This will add the element, resizing the ArrayList if necessary.
list.add(new Object());

5
你可以直接使用ArrayList,它可以为你完成这项工作。

4

无法更改数组大小。 但是,您可以创建一个比原来大的数组,并将一个数组的元素复制到另一个数组中。

如果数组已满,则建议创建两倍大小的数组,如果数组只有一半满,则将其减少到一半。

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

2
你可以使用 ArrayList 代替数组。这样你就可以添加任意数量的元素。
 List<Integer> myVar = new ArrayList<Integer>();

2

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


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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接