java - 如何在不知道数组长度的情况下创建数组

标签 java arrays

我有一个问题需要解决,如下:

Create a method that returns an array that contains only the positive values of another int[] a

我通过编写这个方法解决了这个问题:

public static int[] soloPositivi(int[] a) {
    int[] pos = new int[a.length];
    int j=0;

    for (int i=0; i<a.length; i++){
        if (a[i]>0) {
            pos[j] = a[i];
            j++;
        }
    }
    return pos;
}

当然,当我使用以下示例进行测试时:

int[] a = new int[] {2,-3,0,7,11};

我得到[2,7,11,0,0] ,因为我设置:

int[] pos = new int[a.length];

问题是,如何让 pos 数组具有模块化长度,以便我可以获得 [2,7,11] ,而不必使用列表?我必须仅使用数组方法来解决这个问题。

最佳答案

首先循环统计正数元素的个数,知道长度,然后再次循环复制。

public static int[] copyPositiveVals(int[] arr) {
    int count = 0;
    for(int x : arr) {
        if (x > 0) count++;
    }

    int[] arr2 = new int[count];
    int i = 0;
    for(int x : arr) {
        if (x > 0) {
             arr2[i] = x;
             i++;
        }
    }
    return arr2;
}

关于java - 如何在不知道数组长度的情况下创建数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37762195/

相关文章:

java - 如何打印出 hashmap 中的所有键?

java - 如何获取 jasperreport 文件 (.JRXML) 加载到系统的确切位置?

sql - 如何将 JSON 数组解析为 SQL 表

c# - struct c#中的安全固定大小数组

arrays - Swift 无法使用类型为 'find' 的参数列表调用 '([Score], Score)',其中 Score 是一个结构

javascript - 从两个对象的数组生成对象

java - 无法实例化 Activity ComponentInfo 空指针异常

java - 空白ST : return first entry larger than the key

c - Strtok 返回错误数据

java - 定义新变量