将int添加到int []列表中

时间:2015-09-18 13:44:23

标签: java

我正在尝试学习Java,并且我有一些关于如何向列表中添加int的问题。该分配要求返回一个需要返回int[]列表的函数。我发现int[]不支持.add()功能。

到目前为止我一直在做的事情是这样的:

/**
 * Return all prime numbers until n
 */
public static int[] primesTo(int n) {
    // New list
    int x     = 0;
    int count = 0;

    // First loop to find the amount of results
    for(int i = 2; i <= n; i = i + 1) {
        if(isPrime(i)) {
            count = count + 1;
        }
    }

    // We now know the length of the list we need to create
    int[] result = new int[count];

    // First loop to find the amount of results
    for(int i = 2; i <= n; i = i + 1) {
        if(isPrime(i)) {
            result[x] = i;
            x++;
        }
    }

    return result;
}

当然,这真的很麻烦。我想知道是否还有另一种更漂亮的方法可以在返回int[]时获得相同的结果。

3 个答案:

答案 0 :(得分:1)

如果您还在学习Java,那么本课程很可能是为了让您了解数组的工作原理,尤其是它们的灵活性。稍后,您将使用列表或其他集合执行相同的操作。如果你的任务是返回一个int [],而你还没有学过关于列表的话,也许你的目标是在学习更抽象的方法来做同样的事情之前先用艰难的方法做到这一点。

不要打折基础知识,知道如何正确使用数组是一项宝贵的技能。

答案 1 :(得分:0)

由于你有java 8,你可以使用Stream API以优雅的方式做到这一点。

    public static int[] primesTo(int n) {   
        return IntStream.range(2, n+1).filter(YourClass::isPrime).toArray();        
    }

当你更熟悉这门语言时,你应该学习它,或许以后,这是一个很好的java。

答案 2 :(得分:-1)

您应该只使用List。添加所需的一切,然后返回list.ToArray()。在这种情况下,它仍会返回int[]

/**
 * Return all prime numbers until n
 */
public static int[] primesTo(int n) {
    // We now know the length of the list we need to create
    List<Integer> result = new ArrayList<>();

    // First loop to find the amount of results
    for(int i = 2; i <= n; i = i + 1) {
        if(isPrime(i)) {
            result.add(i);
        }
    }

    return result.toArray(new int[result.size()]);
}