0

In Java, when I'm building up a new array based on an array that's taken in as a parameter. For example, say I want to build an array with all values of the given array except for the sevens, so I want to take {5,7,8,9,7,3} and return {5,8,9,3} without modifying the input array. In python, this would be very simple, and I would do something like this:

def no7s(x):
   y=[]
   for num in x:
      if num!=7:
         y+=[num]
   return y

In java this seems much more complicated. Here's what I've tried:

public static int[] no7s(int[] x){
        int size=0;
        for (int num: x){
            if (num!=7){
                size+=1;
            }
        }
        int[] y = new int[size];
        for (int i=0; i<x.length; i++){
            if (x[i]!=7){
                y[i]=x[i];
            }
        }
        return y;
    }

I'm getting confused about the last for loop; what I have now does not work, but I'm not sure what I should be doing instead. I'm pretty sure the issue is that x.length>size, but I don't know how to account for this.

pwag
  • 1
  • 1
  • 1
    Does this answer your question? [Java dynamic array sizes?](https://stackoverflow.com/a/1647277/1453822) – DeepSpace Jan 15 '21 at 16:31
  • I second @DeepSpace's suggestion. Learn to use a dynamic data structure like an `ArrayList` rather than a raw array. If you need a raw array in the end, you can turn the created `ArrayList` object into an array as the last step. – CryptoFool Jan 15 '21 at 16:34

2 Answers2

2

In Java the answer to this is streams.

Here is no7s rewritten with streams:

public static int[] no7s(int[] x) {
    return Arrays.stream(x)
        .filter(i -> i != 7)
        .toArray();
}

Make sure to include import java.util.Arrays; at the top of your java file.

Adam Griffiths
  • 680
  • 6
  • 26
  • 60
1

In general, do not try to optimize your code on such trivial things as arrays size. There are several layers of optimization in the JVM and lower levels.
You want to focus on higher level optimization (multi-threading, resource pooling, etc).

If you want to use imperative style (old fashion):

int[] toCopy = {5,7,8,9,7,3};

List<Integer> array = new ArrayList<>();
for (int current : toCopy) {
    if (current != 7) {
        array.add(current);
    }
}

If you want to use streams (recommended), see Adam Griffiths's answer :

public static int[] no7s(int[] x) {
    return Arrays.stream(x)
        .filter(i -> i != 7)
        .toArray();
}

If not already done, I strongly advise to take a look on Object Oriented Programming as it's what Java is all about.
I also recommend to use functional programming (like streams, introduced in Java 8) as it's way more simple to read and maintain once accustomed to.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
terrasson marc
  • 97
  • 1
  • 10