1

I have researched and tried for hours to solve my problem, but the reality is that I can't find anything on it. It is simple really. I need to initialize java arrays of undefined size, and then compare the two. In the process of testing my program, when I have defined the array to a specific length (for example)

int[] array = new int[6];

the code waits until I have entered the six objects to move on to the next segment of code, because it is waiting for 6 integers as defined as the array length. But I can't define the array using

int[] array = {};

it obviously won't work, since array.length function will be 0.

My code is below.

import java.util.Scanner;
import java.util.Arrays;
public class Test {
    public static void main(String[] args){

        Scanner input = new Scanner(System.in);


        // My problem is in the definition of the arrays or the for loops defining them below.
        int[] list1 = new int[]; // undefined
        int[] list2 = new int[]; // undefined
        // ask user to fill the two arrays to see if they are equal
        System.out.print("Enter list one >> ");

        for (int i = 0; i < list1.length; i++){
            list1[i] = input.nextInt();
        }

        System.out.print("Enter list two >> ");

        for (int i = 0; i < list2.length; i++){
            list2[i] = input.nextInt();
        }


        // call the equality testing method and output whether or not the two lists are strictly identical or not.
        if (equals(list1, list2) == true)
            System.out.println("The two lists are strictly identical");
        else
            System.out.println("The two lists are not strictly identical");

    }

    // this method 
    public static boolean equals(int[] list1, int[] list2){
        boolean bool = false;
        if (Arrays.equals(list1, list2))
            bool = true;
        else
            bool = false;

        return bool;
    }
}
  • 2
    Arrays on initialization needs to have the size specified. For undefined sizes use arraylists, vectors etc. – Ashish Mathew Dec 01 '17 at 14:50
  • 1
    `if(equals(list1, list2) == true)` is the same thing as `if(equals(list1, list2))`, and in your equals method, you can just use `return Arrays.equals(list1, list2);` – phflack Dec 01 '17 at 14:51
  • `the software (netbeans) waits until I have entered the six objects to move on to the next segment of code` - this is because you're looping 6 times to add to the array? Is there any java issue with using `int[] array = new int[6];`? – phflack Dec 01 '17 at 14:52
  • You can look this how to dynamic array in java – ramazankul Dec 01 '17 at 14:59
  • @ramazankul links are formatted `[pretty](url)` – phflack Dec 01 '17 at 15:00
  • It cannot work without the specified size, because its length is 0 and you will get out of bound runtime exception when try to insert an item ( `java.lang.ArrayIndexOutOfBoundsException`). – xxxvodnikxxx Dec 01 '17 at 15:29
  • Btw what is interesting un-inicialized `int[] foo = null` array gives me the length also 0, but no exception :O and it works same as unsized array, while inserting also out of bound excp. – xxxvodnikxxx Dec 01 '17 at 15:32
  • @xxxvodnikxxx Using `int[] test = null; System.out.println(test.length);` gives me a NPE – phflack Dec 01 '17 at 17:58
  • @xxxvodnikxxx Thanks, but that is not my problematic code segment. It is only initialized as such since I am unclear how I should initialize it. – chickenbiscuit Dec 01 '17 at 19:07

3 Answers3

1

I need to initialize java arrays of undefined size,

You need to use an ArrayList or ask the length at the start.

List<Integer> list1 = new ArrayList<>();
System.out.println("Enter numbers, with a blank line to end");
for (String line; !(line = input.nextLine()).trim().isEmpty(); ) {
     list1.add(Integer.parseInt(line));
}

// later
if (list1.equals(list2))

or use an array

System.out.println("Enter the number of numbers, followed by the numbers");
int[] array1 = new int[input.nextInt()]; // enter the size first.
for (int i = 0; i < array1.length; i++)
    array[i] = input.nextInt();

// later
if (Arrays.equals(array1, array2))

int[] array = {};

it obviously won't work, since array.length function cannot work.

This works as expected and array.length is always 0

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • 1
    Everything is hard coded to 6 elements, I don't think there's a variable amount of elements – phflack Dec 01 '17 at 14:52
  • @phflack in which case there is no reason to create an array of an undefined size as the size would be defined as 6. – Peter Lawrey Dec 01 '17 at 14:54
  • 1
    He's saying the issue is `int[] array = new int[6];` isn't working – phflack Dec 01 '17 at 14:55
  • @phflack which doesn't make sense given this line works fine, it just doesn't appear to do whatever the OP has in mind but it's not clear what that is. – Peter Lawrey Dec 01 '17 at 14:58
  • The way he worded it sounds like it's a netbeans issue, forcing him to define the elements initially (which is a bit unlikely) – phflack Dec 01 '17 at 14:59
  • 1
    @phflack perhaps the distinction between netbeans and the java language isn't clear to the OP and s/he assumes the language supports such a feature but they just don't what it is when it doesn't. – Peter Lawrey Dec 01 '17 at 15:01
  • @phflack the code was meant to posted differently, I was testing the code a bit and didn't change it back. My problem is that I need to created an array with a size defined by how many integers the user enters. – chickenbiscuit Dec 01 '17 at 19:03
  • @PeterLawrey the distinction between netbeans and java is perfectly clear, I was just giving that as an example that the program I am using to code with java supports Java Language. – chickenbiscuit Dec 01 '17 at 19:05
  • 1
    @user8012072 in that case, you should mark this answer as correct. And any text editor works for coding in java, personally I use notepad a lot – phflack Dec 01 '17 at 19:06
0

I am still unable to fulfill what I am really trying to accomplish, but I've used my code to compromise. It is to allow the user to specify the length before entering integers.

import java.util.Scanner;
import java.util.Arrays;
public class Test {
    public static void main(String[] args){
        
        Scanner input = new Scanner(System.in);
        
        System.out.print("How many variables long is the first list? ");
        int n = input.nextInt();
        int[] list1 = new int[n];
        
        System.out.print("How many variables long is the second list? ");
        n = input.nextInt();
        int[] list2 = new int[n];
        
        // ask user to fill the two arrays to see if they are equal
        System.out.print("Enter list one >> ");
        
        for (int i = 0; i < list1.length; i++){
            list1[i] = input.nextInt();
        }
        
        System.out.print("Enter list two >> ");
        
        for (int i = 0; i < list2.length; i++){
            list2[i] = input.nextInt();
        }
        
        
        // call the equality testing method and output whether or not the two lists are strictly identical or not.
        if (equals(list1, list2) == true)
            System.out.println("The two lists are strictly identical");
        else
            System.out.println("The two lists are not strictly identical");
        
    }
    
    // this method 
    public static boolean equals(int[] list1, int[] list2){
        boolean bool = false;
        if (Arrays.equals(list1, list2))
            bool = true;
        else
            bool = false;
        
        return bool;
    }
    

}
0

I see that this question is an older one but I had the same one (or at least similar) and couldn't find answer I was searching for. And now I believe I have the answer for this and would like to share it. Maybe for someone this will be handy.

According to my understanding the question is about creating a single dimensional array with undefined length and the length of this array is going to be increased by the Scanner input. Lot of answers I have seen were about using the ArrayList. But still I wanted to know how to do it with a single dimensional array. First, let me share with you the code and then the explanation:

public class Main {

    static Scanner scanner = new Scanner(System.in);
    final static int ARRAY_MAX_LENGTH = 400_000_000;

    public static void main(String[] args) {


        int[] numbers = createIntArray();

        displayArray(numbers);

    }

    public static int[] createIntArray() {
        int[] ints = new int[ARRAY_MAX_LENGTH];

        System.out.print("Enter numbers: ");
        for (int i = 0; i < ints.length; i++) {
            ints[i] = scanner.nextInt();
            if (ints[i] == 0) {
                break;
            }
        } return ints;
    }

    public static void displayArray(int[] ints) {
        for (int i = 0; i < ints.length; i++) {
            System.out.print(ints[i] + " ");
            if (ints[i] == 0) {
                break;
            }
        }
    }
}

Now the explanation: We want undefined/infinite array length. The truth is: you can not have it. In programming everything has limit. The byte limit is between -128 to 127 the short limit is -32,768 to 32,767 and the int limit is between -2,147,483,648 to 2,147,483,647. So how do you create array with undefined length? Paradoxically: set the array length. And the length should be the maximum length an array can hold. And then create an exit point when you want the array to accept no more inputs from the Scanner class. I solved it by including in my code the if statement with a break keyword (if(input == 0) break;). Once I do not want to make any input with the Scanner class I just type '0' and press enter and the array does not accept any other input and the inputs made before the '0' is saved int the defined int[] numbers array.


Now coming back to the array max length... I found articles that the array max length is the int max length minus 8 (or something similar). This didn't work for me. I read some posts here on Stack Overflow that the array length depends on the JVM and on other factors I have not explored further. I thing the max array length depends on some settings too but I don't want to lie. This is why I set my array length to 400 000 000. When I set the length to 500 000 000 I got the error:

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

If you want to use this code just figure out what is your max array length and use it.


For me this problem was interesting to think about but definitely I would not use it in big programs. It is not efficient at all. For newbies: if you have just learned the one dimensional array, be patient, ArrayList is coming in your later studies and it could make things easier.

redPanther
  • 13
  • 3