在java中声明一个没有大小的数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31439524/
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-11 11:08:16  来源:igfitidea点击:

Declare an array in java without size

javaarrays

提问by Christos Michael

Hello am trying to declare an array in java but i do not want the array to have a specific size because each time the size must be different.

您好,我正在尝试在 Java 中声明一个数组,但我不希望该数组具有特定大小,因为每次大小都必须不同。

I used this declaration: int[] myarray5;

我使用了这个声明: int[] myarray5;

but when am trying the below code there is an error on myarray5

但是当我尝试下面的代码时,myarray5 出现错误

for(int i=0; i<=myarray1.length - 1; i++){
    for (int j=0; j<=myarray2.length - 1; j++){
        if (myarray1[i] == myarray2[j]){
            myarray5[k] = myarray2[j];
            k++;
        }       
    }       
}

and also when am printing the array:

以及在打印数组时:

for (int i=0; i<=myarray3.length-1; i++){
    System.out.print(myarray3[i]+",");
}

采纳答案by Denis Lukenich

There is a NullPointerExceptionbecause you declared but never initialized the array.

有一个NullPointerException因为您声明但从未初始化数组。

You can dynamically declare an array as shown below.

您可以动态声明一个数组,如下所示。

  int size = 5; // or anyother value you want
  int[] array = new int[size];

Or you use a list. Which allows to dynamically change the size. E.g:

或者你使用一个列表。这允许动态更改大小。例如:

  List<Integer> list = new ArrayList<>();
  list.add(5); //adds number 5 to the list
  int number = list.get(0); // Returns Element which is located at position 0 (so in this example in number will be "5");

回答by user3437460

i do not want the array to have a specific size because each time the size must be different.

我不希望数组具有特定大小,因为每次大小都必须不同。

Arrays in Java have fixed size. Once declared, you cannot change it. If you try to force you way. You are creating a new array each time. Please do not create array1to arrayNfor any reasons.

Java 中的数组具有固定大小。一旦声明,你不能改变它。如果你试图强迫你的方式。您每次都在创建一个新数组。请不要array1arrayN任何理由创建。

If you want dynamic size, which can stretch and shrink. You are looking for ArrayList. ArrayList in Java is easy to use.

如果您想要动态大小,可以拉伸和收缩。您正在寻找ArrayList. Java 中的 ArrayList 很容易使用。

ArrayList<Type> arrayList = new ArrayList<>();

or

或者

List<Type> arrayList = new ArrayList<>();

but when am trying the below code there is an error on myarray5

但是当我尝试下面的代码时,myarray5 出现错误

And I guess that would be an ArrayIndexOutOfBoundsExceptionbecause your loops based on array1's length, but your other arrays like array5is having different length.

我想那是ArrayIndexOutOfBoundsException因为你的循环基于 array1 的长度,但你的其他数组的长度array5不同。

回答by user3437460

Why are you using nested loops on 1D-Arrays? This is the problem when you have N-arrays. It makes your codes unreadable and hard to maintain.

为什么在一维数组上使用嵌套循环?当您有N-arrays. 它使您的代码不可读且难以维护。

As other posts has mentioned, use arrayList.

正如其他帖子所提到的,使用 arrayList。

Alternatively, if for any reasons, you cannot use ArrayList. At least make your initial array size large enough to handle all scenarios. This way, you don't need to worry about stretching your array's size.

或者,如果出于任何原因,您不能使用 ArrayList。至少使您的初始数组大小足够大以处理所有情况。这样,您无需担心拉伸数组的大小。

I also noticed your for-loop for printing the array looks bulky.

我还注意到用于打印数组的 for 循环看起来很笨重。

To print an array, you could:

要打印数组,您可以:

for (int i=0; i<myarray.length; i++)    //throw away the = and the -1
    System.out.print(myarray[i] + ",");

OR

或者

for (int i : myarray)    //use a for-each loop
    System.out.print(i + ",");

OR

或者

System.out.println(Arrays.toString(myarray));

回答by SomeStudent

Couple of things, as people have said regular arrays in Java must be declared with a "new" statement as well as a size. You can have an empty array if you want, but it will be of size 0.

有几件事,正如人们所说,Java 中的常规数组必须用“new”语句和大小声明。如果需要,您可以拥有一个空数组,但它的大小为 0。

Now, if you want a dynamic array you can use an ArrayList. Its syntax is as follows:

现在,如果你想要一个动态数组,你可以使用 ArrayList。其语法如下:

ArrayList<Primitive_Type_Here> = new ArrayList<Primitive_Data_Type_Here>();

Now, once again if you do not tell the array what to have then there is no point in even doing anything with either array type. For ArrayLists you would have to tell it to add any object that fits its type. So for example I can add "Hello World" into an ArrayList we can do the following code.

现在,再一次,如果您不告诉数组该拥有什么,那么即使对任一数组类型执行任何操作也毫无意义。对于 ArrayLists,您必须告诉它添加适合其类型的任何对象。例如,我可以将“Hello World”添加到 ArrayList 中,我们可以执行以下代码。

ArrayList<String> sList = new ArrayList<String>();
sList.add("Hello World");
System.out.println("At index 0 our text is: " + sList.get(0));

//or if you want to use a loop to grab an item
for(int i = 0, size = sList.size(); i < size; i ++)
{
   System.out.println("At index " + i + " our text is: " + sList.get(i));
}

**If you are wondering why I am using .size() instead of .length is because arrayLists do not have a .length method, and .size does the same thing for it.

**如果你想知道为什么我使用 .size() 而不是 .length 是因为 arrayLists 没有 .length 方法,而 .size 为它做同样的事情。

**if you are wondering why I have int = 0, size = sList.size(); it is because this way you enhance your code performance as your loop is of O(n) complexity, however if we were to do i < sList.size() it would be O(n) * sList.size() as you would constantly be calling sList.size() per iteration of your loop.

**如果你想知道为什么我有 int = 0, size = sList.size(); 这是因为通过这种方式您可以提高代码性能,因为您的循环具有 O(n) 复杂度,但是如果我们要这样做 i < sList.size() 它将像您一样 O(n) * sList.size()每次循环迭代不断调用 sList.size() 。

回答by Ivan Pavi?

Well what you need is list. Array has to have size because how arrays work.

那么你需要的是列表。数组必须有大小,因为数组是如何工作的。

This is VERY oversimplified explanation:

这是非常简单的解释:

When you declare an array of size 5

当你声明一个大小为 5 的数组时

JVM reservs 5 spots for that array and memorize only pointer to first element.

JVM 为该数组保留 5 个位置,并且只记住指向第一个元素的指针。

3rd element of that array JVM goes for pointer to 1st element + 3.

该数组 JVM 的第三个元素指向第一个元素 + 3 的指针。

List, on the other hand keeps pointer to the first element, and in each element pointer to the next one. So if you want 5th elemnt JVM goes to the 1st element and in it finds memory location of 2nd, in second element find location of 3rd element.

另一方面,List 保留指向第一个元素的指针,并在每个元素中保留指向下一个元素的指针。因此,如果您想要第 5 个元素,JVM 会转到第一个元素,并在其中找到第二个元素的内存位置,在第二个元素中找到第三个元素的位置。

Conclusion: Ordinating trough array is much faster but it has to be fixed size, ordinating trough list is slower but you can add and remove elements as you wish.

结论:排序槽数组要快得多,但它必须是固定大小,排序槽列表较慢,但您可以根据需要添加和删除元素。

And your problem is that probably you don't declare size of your array or you don't initialize your array at all.

而您的问题是,您可能没有声明数组的大小,或者根本没有初始化数组。

回答by Simbarashe Nicholas Chitovhoro

The array should be declared outside the method and have the array passed in as a parameter to the method i.e.

数组应该在方法之外声明,并将数组作为参数传递给方法,即

methodName(int[] anySizeArray){
    //TODO your code here!;
}

Your program should be now able to handle an array of any size.

您的程序现在应该能够处理任意大小的数组。