Java dynamic array sizes?
No you can't change the size of an array once created. You either have to allocate it bigger than you think you'll need or accept the overhead of having to reallocate it needs to grow in size. When it does you'll have to allocate a new one and copy the data from the old to the new:
int[] oldItems = new int[10];
for (int i = 0; i < 10; i++) {
oldItems[i] = i + 10;
}
int[] newItems = new int[20];
System.arraycopy(oldItems, 0, newItems, 0, 10);
oldItems = newItems;
If you find yourself in this situation, I'd highly recommend using the Java Collections instead. In particular ArrayList
essentially wraps an array and takes care of the logic for growing the array as required:
List<XClass> myclass = new ArrayList<XClass>();
myclass.add(new XClass());
myclass.add(new XClass());
Generally an ArrayList
is a preferable solution to an array anyway for several reasons. For one thing, arrays are mutable. If you have a class that does this:
class Myclass {
private int[] items;
public int[] getItems() {
return items;
}
}
you've created a problem as a caller can change your private data member, which leads to all sorts of defensive copying. Compare this to the List version:
class Myclass {
private List<Integer> items;
public List<Integer> getItems() {
return Collections.unmodifiableList(items);
}
}
Variable length (Dynamic) Arrays in Java
Yes: use ArrayList.
In Java, "normal" arrays are fixed-size. You have to give them a size and can't expand them or contract them. To change the size, you have to make a new array and copy the data you want - which is inefficient and a pain for you.
Fortunately, there are all kinds of built-in classes that implement common data structures, and other useful tools too. You'll want to check the Java 6 API for a full list of them.
One caveat: ArrayList can only hold objects (e.g. Integers), not primitives (e.g. ints). In MOST cases, autoboxing/autounboxing will take care of this for you silently, but you could get some weird behavior depending on what you're doing.
Dynamic array length
You could just use an ArrayList
.
import java.util.Scanner;
import java.util.ArrayList;
Scanner in = new Scanner(System.in);
ArrayList<Double> arr = new ArrayList<Double>();
while (in.hasNextDouble()) {
arr.add(in.nextDouble());
System.out.println("Continue? y = 1, n = 2");
if (in.hasNextInt() && in.nextInt() == 2) // assumes any non-2 answer is "Yes"
break;
}
For the sake of brevity, I am omitting the user interaction code.
Also, I'm using Double
s instead of float
s because Double
s have more precision.
Dynamic array in java
An array of dynamic size isn't possible in Java - you have to either know the size before you declare it, or do resizing operations on the array (which can be painful).
Instead, use an ArrayList<Integer>
, and if you need it as an array, you can convert it back.
List<Integer> sum = new ArrayList<>();
for(int i = 0; i < upperBound; i++) {
sum.add(i);
}
// necessary to convert back to Integer[]
Integer[] sumArray = sum.toArray(new Integer[0]);
How can I make a dynamic array in Java?
Using some kind of List
is a better choice, as it basically does what you want (can grow and shrink), in fact, ArrayList
is just that, a dynamic array.
You can hand roll your own if you can't use a List
using System.arraycopy
For example, this will grow or shrink an array to match the size you provide...
public String[] updateArray(String[] src, int size) {
String[] dest = new String[size];
if (size > src.length) {
System.arraycopy(src, 0, dest, 0, src.length);
} else {
System.arraycopy(src, 0, dest, 0, size);
}
return dest;
}
Again... List
is easier...
Dynamic resizing of Array in Java
When you write:
arr=new int[N]
you actually discard your array object and create a new array of int of size N. This new object will not contain your previous array's values.
If you create a larger array, you must copy the previous values to it.
Better still, use one of Java's data structures such as Vector<Integer>
or ArrayList<Integer>
. These use dynamic arrays, but you don't have to know about it and shouldn't worry - they just work...
Dynamic arrays vs Variable-length arrays
There are four kind of arrays:
1) Dynamic Arrays
2) Variable-length Arrays
3) Fixed-length Array
4) Static array
Let's consider the four arrays in more details.
1) Dynamic array
In this case there is an API in array which alter length
variable.
It can be a method that directly modifies the length
setSize(int newLength)
or a methods that modify it indirrectly:
add(Object newElement)
remove(Object toBeRemoved)
Both of these methods modify the length after adding/removing an element.
Example in Java that emulates Dynamic array:
java.util.ArrayList
2) Variable-length array
Variable-length array is a special case of Dynamic array.
In this case length
is read-only and there is no API in array which modifies this variable.
But this variable can be changed by the system the other ways.
Example in Java that emulates Variable-length array - regular java arrays like int[]
.
Lets consider the example:
int[] a = new int[5]; System.out.println(a.length);
a = new int[10]; System.out.println(a.length);
In this case length
variable is changed but we cannot modify it directly like
a.length = 20;
3) Fixed-length array
Fixed-length array is a special case of Variable-length array.
In this case once assigned a value to the length
, we cannot modify it anymore.
But it is important to note that length
variable is still determined at runtime
Example in Java that emulates this behaviour: final array variables like final int[]
.
Lets consider the example:
final int[] a;
if (someVar > 0) { a = new int[100]; } else { a = new int[200]; }
In this case a.length is either 100 or 200 and still determined at runtime.
4) Static array
Static array is a special case of Fixed-length array.
In this case length
not only can be changed but also can be determined at runtime.
Example of such array in Java can be the following construction:
{1, 2, 3, 100, 200, 500}
This constuction can be assigned to a variable only while its initialization
int[] a = {1, 2, 3};
But if we try reassignment like
a = {1, 2};
we get compilation error.
Example in Java that emulates such an array:
final int[] a = {1, 2, 3};
Related Topics
Java: Recommended Solution For Deep Cloning/Copying an Instance
How to Write Contents of a Java Inputstream to an Outputstream
Want Current Date and Time in "Dd/Mm/Yyyy Hh:Mm:Ss.Ss" Format
Difference Between Wait() and Sleep()
Junit Test For System.Out.Println()
How to Convert Java.Util.Date to Java.Sql.Date
How to Format the Day of the Month to Say "11Th", "21St" or "23Rd" (Ordinal Indicator)
How to Capitalize the First Character of Each Word in a String
Difference Between String Object and String Literal
Java Swing Revalidate() VS Repaint()
How to Run a Batch File from My Java Application
Received Fatal Alert: Handshake_Failure Through Sslhandshakeexception
How to Remove Objects from an Array in Java
Nullpointerexception When Creating an Array of Objects
What Are Functional Interfaces Used For in Java 8