1

So I'm trying to make a new Array of different length in a separate method by passing in an array from the main method but I'm having trouble. Essentially what I'm trying to do is make it so my starting array values of

 int [] myInches = {89,12,33,7,72,42,76,49,69,85,61,23};

get transferred to my createLowerArray method, and by comparing it to user input maxParam, creates a new array and returns it.

   public static int [] createLowerArray(int maxParam, int [] myInchesParam) {
    int [] betterInches = {0,0,0,0,0,0,0,0,0,0};
    for (int i = 0; i < myInchesParam.length; i++) {
        if (myInchesParam[i] < maxParam) 
            betterInches[i] = myInchesParam[i];
    } 
    return betterInches;
}

So let's say the user inputs "40", it would see if the corresponding elements in myInches/myInchesParam were smaller or not, and if they were, would replace the array I created in that method with it's corresponding value. So since 12, 33, 7, and 23 are the only elements less than 40, it should make an array of length 3 with position 0 being 12, [1] = 12, [2] = 7, and [3] = 23. I know you can't make an array bigger than it already is due to memory issues but It's possible to make one smaller from what it already is right? If that's not possible either than I'd like to know how to get this result as at the moment the array it returns is of the same length as the original with incorrect element positions which is not what I wish to do. Thank you in advance for any help.

  • 4
    you can nit change the size of an array. A new one need to be created, eventually using some of the methods of `Arrays` (e.g. `copyOf()`). Or easier use an `ArrayList` to create a list with can then be converted to an array Even better (IMO) using streams (`Arrays.stream(...).filter(...).toArray()`) – user85421 Apr 12 '19 at 05:22
  • instead of using myInchesParam.length; in for loop why don't you use betterInches.length; ? or you can use List data structure. – Onkar Musale Apr 12 '19 at 05:22

3 Answers3

2

You cannot change the length of an already-created array. That means you cannot increase or decrease the size. You have a few options here. First, you could use an ArrayList. The benefit of using lists is that they have built-in functions that let you increase and decrease the length of your data.

The other option (which doesn't require ArrayLists) would be to not create the array until you know how long (or how short) it needs to be. To do this, you could write one for-loop that counts the number of items that you want to add to the new array. Then, after that loop, you create an array of that length. Finally, you write a second second for-loop that add the elements to the newly created array.

Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55
EKW
  • 2,059
  • 14
  • 24
  • can you do this without ArrayList?? – Vishwa Ratna Apr 12 '19 at 05:26
  • @CommonMan Yes. That is the second option that I mentioned. – EKW Apr 12 '19 at 05:26
  • @CarlosHeuberger, i know `ArrayList` will make things simpler in terms of reducing the size, but if the the implementation could be done with a `new array` or similar then it would reduce the overhead of imports in program. – Vishwa Ratna Apr 12 '19 at 05:28
  • `ArrayList` perform the implementation of array under the **hood**. Your solution is not wrong but what is the use if i can give another answer in java-8 `stream` now, will it solve the problem?? Yes it will solve the problem and will be even efficient, but it does not quench the solution, the solution asked regarding Array only so you must try to get the possible solution with just that, *if it was possible* , yes it is. – Vishwa Ratna Apr 12 '19 at 05:38
  • Think, if someone asked question asked you regarding binary sort and you without using binary sort give answer `Collection.sort()`, though it may be not wrong but doesn't fulfill the context. – Vishwa Ratna Apr 12 '19 at 05:38
  • @CommonMan That is why I included the other option, which only uses vanilla arrays, and doesn't require any additional imports. – EKW Apr 12 '19 at 05:40
  • I read it now @EKW, the second edit seems fine. Just a bit code implantation will showcase more. – Vishwa Ratna Apr 12 '19 at 05:42
  • actually the questoin was about reducing the size of an array, so the correct answer is just "No, array size can't be changed" – user85421 Apr 12 '19 at 05:45
  • @CarlosHeuberger That's the first sentence of my answer. – EKW Apr 12 '19 at 05:45
  • Things are getting heated I see, no but seriously thank you for this. The thought of lists didn't even cross my mind and I figured I was stuck with loops. I'll try the loop method you mentioned since I need more practice and if that goes South I'll give lists a try. Thanks once again. – Confused Student Apr 12 '19 at 05:47
1

To do this, You can make use of a List.

Try this:

public static int [] createLowerArray(int maxParam, int [] myInchesParam) {
    List<Integer> betterInches= new ArrayList<Integer>();
    for (int i = 0; i < myInchesParam.length; i++) {
        if (myInchesParam[i] < maxParam) 
            betterInches.add(myInchesParam[i]);
    } 
    Integer[] returnedInches= betterInches.toArray();
    return returnedInches;
}
preciousbetine
  • 2,959
  • 3
  • 13
  • 29
  • cant you do this with just array?? – Vishwa Ratna Apr 12 '19 at 05:24
  • @CommonMan , I think a list was meant for this because: It's size is changed dynamically when items are added. – preciousbetine Apr 12 '19 at 05:26
  • getting an `array` at the end seems better than your precious version, i would appreciate if you could add another answer as part 2 with just `new Array` as it would fix the current situation with the minimal need of imports. – Vishwa Ratna Apr 12 '19 at 05:31
  • @CommonMan you are aware that imports don't cost, eventually they shrink the size of your source... you are just importing the *namespace*, there is no class or lib being imported or such (you can avoid imports at all by just using full qualified names everywhere {and making code harder to **read**}, result compiled class will be the same) – user85421 Apr 12 '19 at 05:39
  • @CarlosHeuberger , **There is no runtime cost from using an import statement The compilation process can take a little more time with an import statement The compilation process can take even more time with a wildcard import statement For improved readability, wildcard import statements are bad practice for anything but throwaway classes The compilation overhead of non-wildcard import statements are minor, but they give readability benefits so best practice is to use them** ref: http://www.javaperformancetuning.com/news/qotm031.shtml – Vishwa Ratna Apr 12 '19 at 05:45
  • For some reason the last two lines are telling me that they're incompatible types. The second to last line says "java.lang.object cannot be converted to java.lang.Integer" while the last line says "java.lang.Integer cannot be converted to int []". Did I type one too many variables? I typed it out just how it was put, if all else fails though I can always try for the loop method after all. – Confused Student Apr 12 '19 at 06:02
0

An Array has per definition the size you give it when you initialise it. So sadly you won't be able to change the size of the array dynamically. What you can do is to create a new array with the according size or try to work with ArrayLists (or any List likewise). Depending on how your array size calculates you can even calculate the size before creating it and then set the correct size of your array on initialisation.

Example for creating a ArrayList can be found here.

or how @preciousbetine suggested you can rewrite your method to something like that (it's all written without any additional library)

public static int [] createLowerArray(int maxParam, int [] myInchesParam) {
        List<Integer> betterInches= new ArrayList<>();
        Arrays.stream(myInches)
            .forEach(inches -> {
                if (inches < maxParams) {
                    betterInches.add(inches);
                }
            });
        return betterInches.toArray();
    }
TheOddCoder
  • 161
  • 1
  • 12