java中的动态数组声明

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4054255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 11:02:31  来源:igfitidea点击:

Dynamic array declaration in java

javaarrays

提问by raju

can anyone tell me the error in this java declaration String[][] t=new String[15][15];this works fine and if i use String[][] t=new String[][];because i need to declare the variable t as dynamic as i am not sure how much values i am going to store in t.

谁能告诉我这个 java 声明中的错误String[][] t=new String[15][15];这工作正常,如果我使用String[][] t=new String[][];因为我需要将变量 t 声明为动态的,因为我不确定我将在 t 中存储多少值。

回答by Mark Baijens

Use ArrayList (or other array object who can handle any number of objects). A java array always has a fixed length since some memory will be reserved for the array.

使用 ArrayList(或其他可以处理任意数量对象的数组对象)。java 数组始终具有固定长度,因为将为数组保留一些内存。

ArrayList creates such array as well to store the objects. Of you add more abjects as the current reserved size of the array than ArrayList will create a new bigger array (+50% if i'm correct). There are some other implementations that act a bit different (for example they create a new array 100% of the original one when the array is full. If performance is really important for you than you can look into this.

ArrayList 也创建这样的数组来存储对象。你添加更多的对象作为数组的当前保留大小,而不是 ArrayList 将创建一个新的更大的数组(如果我是正确的,+50%)。还有一些其他实现的行为有点不同(例如,当数组已满时,它们会创建一个 100% 的原始数组的新数组。如果性能对您来说真的很重要,那么您可以研究一下。

ArrayList<ArrayList<String> t = new ArrayList<ArrayList<String>();

void fill() {
    ArrayList<String> t2 = new ArrayList<String>();
    t2.add("somestring");
    String s = "someotherstring";
    t2.add(s);
    t.add(t2);
}

回答by Brad Mace

If you don't know how big it needs to be just declare it as

如果您不知道它需要多大,只需将其声明为

String[][] t;

and once you know how big it needs to be you can do (beforetrying to use the array)

一旦你知道它需要多大,你就可以做(尝试使用数组之前)

t = new String[15][15];

If you're never sure how big the array need to be, you'll need to use something like a List of Lists.

如果您永远不确定数组需要有多大,则需要使用列表之类的东西。

List<List<String>> t = new ArrayList<List<String>>;

public void add(String str, int row, int col) {
    while (row >= t.size())
        t.add(new ArrayList<String>());

    List<String> row_list = t.get(row);
    while (col >= row_list.size())
        row_list.add("");

    row_list.set(col, str);
}

回答by DJClayworth

In Java array objects are always of fixed length. Once you have allocated them you cannot change their size. An array variablecan be made to point to different array objects of different size. So you can allocate:

在 Java 中,数组对象总是固定长度的。一旦你分配了它们,你就不能改变它们的大小。可以使数组变量指向不同大小的不同数组对象。所以你可以分配:

String[][] t;

which doesn't point to an object and allocate an object later once you know the size:

一旦你知道大小,它不指向一个对象并稍后分配一个对象:

int n1,n2;
// calculate n1,n2
t = new String[n1][n2];

If you need a structure where the size can change you are much better off using ArrayList, which can be dynamically resized.

如果你需要一个可以改变大小的结构,你最好使用 ArrayList,它可以动态调整大小。

回答by Mike Edwards

As bemace said, just because you are declaring the variable doesn't mean you have to initialize it immediately.

正如 bemace 所说,仅仅因为您声明了变量并不意味着您必须立即初始化它。

As Mark said, arrays have a fixed size. Once an array is initialized(not declared, initialized) it has a fixed size.

正如马克所说,数组有固定的大小。一旦数组被初始化(未声明,初始化),它就有一个固定的大小。

So, there are two possibilities:

所以,有两种可能:

Either you will know how big the array needs to be before you need to start using it, in which case you can simply delay your initialization as suggested by bemace.

要么在需要开始使用数组之前就知道该数组需要多大,在这种情况下,您可以简单地按照 bemace 的建议延迟初始化。

Or you won't know how big it needs to be before you start using it, in which case you need to use a dynamically sized data structure(s). Check out the Java Collections API:

或者您在开始使用之前不知道它需要多大,在这种情况下,您需要使用动态大小的数据结构。查看 Java 集合 API:

tutorialapi reference

教程api参考

回答by Nrj

Declare it as String [][]t = null;

将其声明为 String [][]t = null;

And Reinitializeit with actual lengthonce you get it.

重新初始化的实际长度,一旦你得到它。

t=new String[x][y];

回答by Stephen P

There are several good answers already, but it has now been revealed in a comment to Mark Baijens' answerthat the purpose of this question is that raju need a key to multi-valuemapping.

已经有几个很好的答案,但现在在对Mark Ba​​ijens 的回答的评论中透露,这个问题的目的是 raju 需要一个多值映射的

Mark followed up that comment by suggesting raju use a HashMap<String, String> hashMap = new HashMap<String, String>();— however that only works for a single key-value pair.

马克通过建议 raju 使用 a 来跟进该评论HashMap<String, String> hashMap = new HashMap<String, String>();- 但是这只适用于单个键值对。

What raju needs is a

raju 需要的是

Map<String, Collection<String>> t
    = new HashMap<String, List<String>>();

Adding the first value for a key requires initialization of a List for that bucket, while adding additional values requires fetching the existing list and adding the new value.

添加键的第一个值需要为该存储桶初始化一个列表,而添加其他值需要获取现有列表并添加新值。

Note I used Collection<String>in the declaration, so it could be a List if the order of values is important, or it could be a Set to prevent duplicate values under the same key.

注意我Collection<String>在声明中使用了,所以如果值的顺序很重要,它可以是一个 List,或者它可以是一个 Set 以防止同一键下的重复值。

This would probably be best implemented as a Class itself, perhaps

这可能最好作为类本身实现,也许

public class MultiValueMap<K, V> extends Map<K, V>
{
    ...
}

so the initialization of the List on the first put(key, value)and the subsequent .add(value)to the list could be hidden in the implementation.

因此,列表的第一个put(key, value)和后续列表的初始化.add(value)可以隐藏在实现中。