Resize an Array while keeping current elements in Java?(在保留 Java 中的当前元素的同时调整数组的大小?)
问题描述
我已经搜索了一种在 Java 中调整数组大小的方法,但我找不到调整数组大小的方法同时保留当前元素.
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:
创建一个所需大小的新数组,然后使用
java.lang.System.arraycopy(...);
使用 java.util.ArrayList<T> 类,当您需要使数组更大时,它会为您执行此操作.它很好地概括了您在问题中描述的内容.
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 中的当前元素的同时调整数组的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在保留 Java 中的当前元素的同时调整数组的大小?
基础教程推荐
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- Struts2 URL 无法访问 2022-01-01
