简体   繁体   English

在java中动态分配数组

[英]Dynamically allocated array of arrays in java

I have a problem with array of arrays object. 我有一个数组数组对象的问题。 I tried the default Java array like this: 我尝试了这样的默认Java数组:

String[][] array = new String[5][5];

And it worked. 它奏效了。 But now I'm facing for another problem. 但现在我面临另一个问题。 I don't know the sizes of the array so I need a dynamically allocated array of arrays. 我不知道数组的大小,所以我需要一个动态分配的数组数组。 I tried this: 我试过这个:

ArrayList<String> array = new ArrayList<>();
ArrayList<ArrayList<String>> arrayOfArrays = new ArrayList<>();

array.add("1");
array.add("2");
array.add("3");
arrayOfArrays.add(array);
System.out.println(arrayOfArrays);
array.clear();
array.add("4");
array.add("5");
array.add("6");
arrayOfArrays.add(array);
System.out.println(arrayOfArrays);

And it prints: 它打印:

[[1, 2, 3]]
[[4, 5, 6], [4, 5, 6]]

And I don't need to rewrite it. 而且我不需要重写它。 It should looks like this: 它应该是这样的:

[[1, 2, 3]]
[[1, 2, 3], [4, 5, 6]]

I'm facing for this problem very long time and I tried a lot of workarounds but I need some clever solution. 我很长时间都面临这个问题,我尝试了很多解决方法,但我需要一些聪明的解决方案。 Also I will appreciate any help. 此外,我将不胜感激任何帮助。

And I have a second question. 我还有第二个问题。 How to add it in cycle? 如何在循环中添加它? Because it has the same output as in the first case. 因为它具有与第一种情况相同的输出。 For example: 例如:

for (int i = 0; i < array.size() - 1; i++) {
    arrayOfArrays.add(swap(array, i, i+1));       
}

You are adding the same ArrayList instance twice to the outer List . 您将相同的ArrayList实例两次添加到外部List

You need to create two distinct ArrayList instances to add to your arrayOfArrays . 您需要创建两个不同的ArrayList实例以添加到您的arrayOfArrays

Replace 更换

array.clear();

with

array = new ArrayList<>();

You should be aware that you're just using the same array object, and add it to the arrayOfArrays twice, that why it prints out the same thing twice. 你应该知道你只是使用相同的array对象,并将它添加到arrayOfArrays两次,这就是为什么它打印两次相同的东西。

What you need is actually this: 你需要的是这个:

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

    ArrayList<String> array1 = new ArrayList<>();
    array1.add("1");
    array1.add("2");
    array1.add("3");
    arrayOfArrays.add(array1);
    System.out.println(arrayOfArrays);

    ArrayList<String> array2= new ArrayList<>();
    array2.add("4");
    array2.add("5");
    array2.add("6");
    arrayOfArrays.add(array2);
    System.out.println(arrayOfArrays);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM