gpt4 book ai didi

java - 如何编写扩展数组容量的通用方法?

转载 作者:行者123 更新时间:2023-12-01 09:38:35 25 4
gpt4 key购买 nike

我想编写一个通用方法来扩展特定类型数组的容量。函数签名可以是这样(不是必须),参数“growth”表示增长容量的数量。

public static T[] ExpandCapacity(T[] array, int Growth)

示例:Integer[] testArray = new Integer[5]; testArray = ExpandCapacity(testArray,5);

执行此函数后,testArray.length应为10。

最佳答案

使用泛型类型 Tstatic方法,您必须使用 <T> 指定它。然后你可以使用 Arrays.copyOf(T[], int) (根据 Javadoc)复制指定的数组,并用空值截断或填充(如果需要),以便副本具有指定的长度。

public static <T> T[] expandCapacity(T[] array, int growth) {
return Arrays.copyOf(array, array.length + growth);
}

关于java - 如何编写扩展数组容量的通用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38625924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com