在 Java 中保留当前元素的同时调整数组大小? [英] Resize an Array while keeping current elements in Java?

查看:28
本文介绍了在 Java 中保留当前元素的同时调整数组大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have searched for a way to resize an array in Java, but I could not find ways of resizing the array while keeping the current elements.

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

I found for example code like int[] newImage = new int[newWidth];, but this deletes the elements stored before.

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

My code would basically do this: whenever a new element is added, the array largens by 1. I think this could be done with dynamic programming, but I'm, not sure how to implement it.

推荐答案

您不能在 Java 中调整数组的大小.您需要:

You can't resize an array in Java. You'd need to either:

  1. 创建一个所需大小的新数组,并使用java.lang.System.arraycopy(...);

使用 java.util.ArrayList 类,当您需要使数组更大时,它会为您执行此操作.它很好地概括了您在问题中所描述的内容.

Use the java.util.ArrayList<T> class, which does this for you when you need to make the array bigger. It nicely encapsulates what you describe in your question.

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

Use java.util.Arrays.copyOf(...) methods which returns a bigger array, with the contents of the original array.

这篇关于在 Java 中保留当前元素的同时调整数组大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆