【问题标题】:How to create an Array without knowing the length it will have [duplicate]如何在不知道长度的情况下创建数组 [重复]
【发布时间】:2016-06-11 09:37:03
【问题描述】:

我有一个问题需要解决:

创建一个返回数组的方法,该数组只包含另一个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],而不必使用列表?我必须只使用数组方法来解决这个问题。

【问题讨论】:

  • 不使用数组而使用列表?
  • 这个问题只能通过使用数组及其方法来解决......如果我可以使用列表我会做到的
  • 使用ArrayList添加有​​效值,然后使用toArray()方法对return一个数组。 docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
  • 您可以查看链接的问题 - 虽然有些答案确实提到了使用列表,但其他人还建议首先计算数组的大小,然后用这个大小创建它。
  • 也有可能用Java8改进代码:int[] arr = new int[] {2,-3,0,7,11};int[] newArr = Arrays.stream(arr).filter(x -&gt; x &gt; 0).toArray();或许也可以加入这个解决方案?

标签: java arrays


【解决方案1】:

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

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 8 更容易:int[] arr = new int[] {2,-3,0,7,11}; int[] newArr = Arrays.stream(arr).filter(x -&gt; x &gt; 0).toArray();
  • @KevinWallis 我相信你的方法也是一个好方法,但我对 java 还是很陌生,我正在寻找一种对初学者友好的方法
  • @Daniele 好的,但也许你也可以让自己对java 8 lambda 表达式友好,它们非常酷且易于使用。比使用默认方式更具可读性(流利):)
猜你喜欢
  • 1970-01-01
  • 2020-12-09
  • 2017-01-12
  • 2016-10-13
  • 1970-01-01
  • 2019-08-08
  • 2019-04-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多