简体   繁体   中英

defining an array size without hardcoding in Java

I'm having a problem where I cannot initialize an array without hard-coding it in Java.

So this is the hard-code version which works:

    int numberOfElements = inputFromFile(args[0], myArray);
    int [] myArray = new int[1000];

inputFromFile is basically going to be a method I'm going to write that can read the numberOfElements from a textfile along with my program.

I tried fixing it without hardcoding and got my result to be this:

    int numberOfElements = inputFromFile(args[0], myArray);
    int [] myArray = new int[numberOfElements];

Problem remains that Eclipse wants me to initialize myArray which is an integer array. Is there any good fixes without hard-coding? Any suggestion would be great.

Use an ArrayList, instead? Java, like C, requires constant sized arrays.

You need to initialize an array before using. You are aware of that, i assume.

If you dont know the size of your data, ie: you wont know how big the array size will be, then you will need to use ArrayList<T> which uses array internally and manages reallocation of array size for you.

If you have to use an array, you will have to maintain the array size yourself. as the array grows, you might run out of buckets if you dont set up enough space for the data ie: IndexOutOfBoundsException etc. Then you need to create a new array copy the content of the current array and then continue. All this is done for you in ArrayList, that s the benefit. Saves you time and implementation. Moreover, there is a concept called load factor which is used to expand the array.

Load factor for array is usually:
(j * 3) / 2 + 1 // j for the current length of the array.

FYI: Copying of array becomes very expensive if you data grows very big.

int numberOfElements = inputFromFile(args[0], myArray);
int [] myArray = new int[1000];

By looking at your code, your order of statements is wrong and should be :

int [] myArray = new int[1000];
int numberOfElements = inputFromFile(args[0], myArray);

you are passing myArray to a method before declaring and initializing it.

ArrayList<Integer> s = new ArrayList<Integer>();
int numberOfElements = inputFromFile(args[0], myArray);

This would be better. Then you need to change your method signature as follows:

public void inputFromFile(String fileName, ArrayList<Integer> collection){
 // your impl.
}

使用和声明数组的各种方法: http//leepoint.net/notes-java/data/arrays/arrays.html

Neither of your code blocks will work, as you try to use myArray before it's declared, or else you try to redeclare myArray . Other than that, if by "hardcode" you mean use a literal value, then no, you don't have to do that. Any of these will work:

int[] arr1 = new int[5];
int size = 10;
int[] arr2 = new int[size];
int sizeLoadedFromFile = loadSizeFrom("/foo/bar/baz");
int[] arr3 = new int[sizeLoadedFromFile];

Note you can also declare an array without an explicit "size" argument if you know the elements ahead of time:

int[] arr4 = {1, 2, 3, 4};

If you think you want an array, but you don't know the size ahead of time, then what you really want is some kind of Collection --probably a List :

List<Integer> list1 = new ArrayList();
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);

or more readably, again if you know the elements ahead of time:

List<Integer> list2 = new ArrayList() {{
    add(1); add(2); add(3); add(4);
}};

or

List<Integer> list3 = Arrays.asList(1, 2, 3, 4, 5);

The Collections Tutorial should tell you anything else you need to know.

I think you are getting the error because

1) you are using myArray before it is declared.

2) return type of the function inputFromFile does not match int.

I think the following program will answer your question. Here I have a int identifier 'm' which is getting set to a value returned by the 'getNumber' method. Then I am declaring an array of size m.

public class Practise {
    public static void main(String args[]){
        int m = getNumber();
        int [] a = new int[m];

        for(int i = 0; i < m; i++)
            System.out.println(a[i]);
    }
    public static int getNumber(){
        Scanner input = new Scanner(System.in);
        int i = 0;
        i = input.nextInt();

        return i;
    }
}
  1. You can provide the size of your array as command line argument.
  2. Using Dependency Injection of Spring can also be a good way to go, I hope you know how to write a simple bean (constructor injection / setter injection ).

An alternative to using List<Integer> is to use the Trove4j TIntArrayList. This is effectively a wrapper for int[] .

However, ArrayList<Integer> is usually fast enough for most use cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM