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

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

问题描述

我已经寻找一种方式来调整Java中的数组,但我无法找到调整的阵列方式的同时保持当前的元素的。我发现例如code像 INT [] = newImage新INT [newWidth]; 但这删除元素之前存储的结果
我的code将基本上做到这一点:每当添加了新的元素,数组largens 1。我认为这可能与动态编程来完成,但是我,不知道如何实现它。

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. I found for example code like int[] newImage=new int[newWidth]; but this deletes the elements stored before.
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<当你需要做出更大的阵列类,它可以实现这个要求; T&GT。它很好地概括你在你的问题描述。

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天全站免登陆