在Java中,没有内置的可变长数组类型,但可以通过以下几种方法实现动态增长数组:
使用`ArrayList`类
`ArrayList`是Java中的一个集合类,它实现了`List`接口,可以动态地增长和缩小。
import java.util.ArrayList;public class DynamicArrayExample {public static void main(String[] args) {ArrayListnumbers = new ArrayList<>(); numbers.add(10);numbers.add(20);numbers.add(30);System.out.println("数组素:");for (int i : numbers) {System.out.println(i);}}}
使用`System.arraycopy`方法
当需要从现有数组创建一个新的、更大的数组时,可以使用`System.arraycopy`方法。
int[] a = {1, 2, 3, 4};int[] b = new int[a.length + 2];System.arraycopy(a, 0, b, 0, a.length);b[a.length] = 5;b[a.length + 1] = 6;System.out.println("扩容后数组a容量为:" + b.length);for (int i : b) {System.out.print(i + " ");}
使用`Arrays.copyOf`方法
`Arrays.copyOf`方法可以创建一个新的数组,其长度为原数组的长度加上指定的增长量。
String[] wordList = new String;int wordCount = 0;int arrayGrowth = 50;while ((strLine = br.readLine()) != null) {String[] temp = Arrays.copyOf(wordList, wordList.length + arrayGrowth);System.arraycopy(wordList, 0, temp, 0, wordList.length);wordList = temp;// Store the content into an arrayScanner s = new Scanner(strLine);while (s.hasNext()) {wordList[wordCount] = s.next();wordCount++;}}
以上方法都可以实现动态增长数组的效果。选择哪种方法取决于具体的应用场景和个人偏好
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/82506.html