如何 return 并从 java 中的方法调用动态一维数组? (我的代码中缺少什么)?

How to return and call a Dynamic 1D Array from a method in java? (What am I missing in my code)?

   public static int createArray(int theListSize)
  {
    ArrayList<Integer> possiblePrimeNum = new ArrayList<Integer>();
    
    for (int i=0; i<=theListSize; i++) //simply creates the array
    {
      possiblePrimeNum.add(i, i+2);
    }
    return possiblePrimeNum;
  } 

我不明白这段代码。我的意思是我明白我要做什么,但我不知道为什么数组不会return。这里有什么问题?

possiblePrimeNum=createArray(theListSize);

您将此方法声明为 return 单个 int 值、单个数字和基元(不是对象)。

一个 ArrayList 是一个 集合 数字,Integer 对象(不是基元)。

你说:

Dynamic 1D Array

我不知道你所说的“动态”是什么意思。

Java 中的数组与 ArrayList 中的数组不同。第一个是 Java 中的内置基本类型。第二个是在 Java Collections Framework 中找到的 class,与所有 Java 发行版捆绑在一起。

您问的是:

I mean that I understand what I'm going to do, but I don't know why the array won't return.

将您的方法更改为 return ListInteger 个对象,而不是单个 int。像这样。

public static List < Integer > possiblePrimes ( final int countOfPrimes )
{
    List < Integer > possiblePrimes = new ArrayList < Integer >( countOfPrimes );
    for ( int i = 0 ; i <= countOfPrimes ; i++ ) 
    {
        possiblePrimes.add( i , i + 2 );
    }
    return List.copyOf( possiblePrimes );  // Return a unmodifiable list, as a general best practice.
}

像这样调用那个方法。

List < Integer > maybePrimes = App.possiblePrimes( 7 );
System.out.println( "maybePrimes = " + maybePrimes );

当运行:

maybePrimes = [2, 3, 4, 5, 6, 7, 8, 9]

我认为您寻找候选素数的算法需要做更多的工作。 ‍

如果你真的想要数组,请参阅:

  • How to convert an ArrayList containing Integers to primitive int array?
  • Convert ArrayList of Integer Objects to an int array?