gpt4 book ai didi

没有大小的 Java ME 字符串数组

转载 作者:搜寻专家 更新时间:2023-11-01 04:03:34 27 4
gpt4 key购买 nike

我有一个简单的问题?

String[] names  = null ;

names[0] = "Hello"

我收到一个错误..

我怎么能实例化数组,因为我不知道大小限制...帮助我

最佳答案

使用 ArrayList<String>当您事先不知道数组大小时。您在此处所做的操作无效(试图访问空对象)。


编辑:因为您不能使用 Vector 和 ArrayList,所以您必须自己实现动态数组。您会在 algolist.net 上找到一个几乎准备就绪的解释。 。只需将 int 存储替换为 String 存储即可。

// Warning: not tested!
public class DynamicStringArray {
private String[] storage;
private int size;

public DynamicArray() {
storage = new String[10];
size = 0;
}

public DynamicArray(int capacity) {
storage = new String[capacity];
size = 0;
}

public void ensureCapacity(int minCapacity) {
int capacity = storage.length;
if (minCapacity > capacity) {
int newCapacity = (capacity * 3) / 2 + 1;
if (newCapacity < minCapacity)
newCapacity = minCapacity;
storage = Arrays.copyOf(storage, newCapacity);
}
}

private void pack() {
int capacity = storage.length;
if (size <= capacity / 2) {
int newCapacity = (size * 3) / 2 + 1;
storage = Arrays.copyOf(storage, newCapacity);
}
}

public void trim() {
int newCapacity = size;
storage = Arrays.copyOf(storage, newCapacity);
}

//...
}

关于没有大小的 Java ME 字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5804127/

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