简体   繁体   中英

How to declare string array[] of unknown size (JAVA)

I want my String[] array; to be static but I still don't know it's size.

Is there any way to declare string array of unknown size? As much as possible I don't want to use ArrayList

You don't need to know the array size when you declare it

String[] myArray;

but you do need to know the size when you initialize it (because Java Virtual Machine needs to reserve a continuous chunk of memory for an array upfront):

myArray = new String[256];

If you don't know what the size will need to be in the moment you initialize it, you need a List<String> , or you'll be forced to make your own implementation of it (which is almost certainly worse option).

No, it needs to be declared, and thus have a length before you can set elements in it.

If you want to resize an array, you'll have to do something like: Expanding an Array?

String [] array = new String[1];

it will be garbage collected later after you init with a real array n elements.

array = new String[n];

ofcourse it has a performance decrease but it should be non-importance unless you repeat same for many different arrays.

列表更适合操纵您不知道长度的“数组”。

Using Java.util.ArrayList or LinkedList is the usual way of doing this. With arrays that's not possible as I know.

Example:

List unindexedVectors = new ArrayList();

unindexedVectors.add(2.22f);

unindexedVectors.get(2);

My apologies to the nay-say-ers, this can be done easily.

import java.util.Random;

public class Roll_2 {
static Random random = new Random();

public static void main(String[] args) {
int[] variableArray1 = init(random.nextInt(9)); // random size
int[] variableArray2 = init(random.nextInt(9)); // random size
int[] variableArray3 = init(random.nextInt(9)); // random size

randomaize(variableArray1); // randomize elements
randomaize(variableArray2); // randomize elements
randomaize(variableArray3); // randomize elements

print(variableArray1);  // print final
print(variableArray2);  // print final
print(variableArray3);  // print final
}
private static int[] init(int x) {
int[] arr = new int[x];
return arr;
}
private static void print(int[] body) {
System.out.print("[");
for (int i=0;i<body.length;i++) {
System.out.print(body[i]);
if (i<body.length-1) System.out.print(" ");
}
System.out.println("]");
}
private static void randomaize(int[] body) {
for (int i=0;i<body.length;i++) {
body[i] = random.nextInt(9);
}
}
}

Sample Run 1: [1 7 2] [5 2 8 6 8 3 0 8] []

Sample Run 2: [2 5 6 8 0 7 0 6] [0 0 1] [2 1 2 1 6]

Sample Run 3: [8 3 3] [7] [1 3 7 3 1 2]

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