i just met up a problem with array.

int[] num = new int[10];

this is everytime we declare and intialization one,
how about to declare and intializate with unkown size?

Recommended Answers

All 5 Replies

You can declare it, but you cannot initialise an array without specifying its size. (The size can be a variable, eg ask user how many, input integer, use that as size to initialise array)

oh, but my practical question require me to develop a program, when user type negative value to end the program, so how? :(

you could use a vector.

A simple way is to use ArrayList class (http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html). Vector should be used if you want to program Thread Safe type because It is slower than ArrayList.

Or if you do not want to use any extra class, you may need to design a way to initialize it. For example, you declare a variable and wait until you know for sure for its size.

int[] anArray;
int arraySize;
boolean done;
do {
  // get the size from user using whatever way you want...
  ...
  if (arraySize>0) {
    anArray = new int[arraySize];
    ...  // do something
  }
  else {
    done = true;
  }
}while (!done);

Perhaps what you would be better off doing is when you want to append to the array, simply create a new array with the new size in its definition, then add the data from the old array to the new array and delete the old array. After that you may then assign the new value at the end of the new array.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.