Resize an Array While Keeping Current Elements in Java

Resize an Array while keeping current elements in Java?

You can't resize an array in Java. You'd need to either:

  1. Create a new array of the desired size, and copy the contents from the original array to the new array, using java.lang.System.arraycopy(...);

  2. Use the java.util.ArrayList<T> class, which does this for you when you need to make the array bigger. It nicely encapsulates what you describe in your question.

  3. Use java.util.Arrays.copyOf(...) methods which returns a bigger array, with the contents of the original array.

Change an array length without creating new one?

You can't modify the size of an existing one but you can reassign a new array to the same variable. You can do it like this.


int[] array = {1,2,3,4};
int newLength = 8;
System.out.println(Arrays.toString(array));
array = java.util.Arrays.copyOf(array,newLength);
System.out.println(Arrays.toString(array));

prints

[1, 2, 3, 4]
[1, 2, 3, 4, 0, 0, 0, 0]

If the newLength is shorter, the end items will be omitted. If it is longer, all the existing items will be copied to an array of the new length.

If you want to have a data structure that dynamically increases in size as needed, then use an ArrayList

how can I resize an array in Java?

You can't do it like that. If you want to dynamically change the size of the array, you would have to use new operator. You have allocate a new array with higher size and then copy all the old elements. Something like below.

int sz = 1;
int[] h = new int[sz];
sz++;
int h1 = new int[sz];
for (int i = 0; i < h.length;++i) {
h1[i] = h[i];
}
h = h1;
h[1]=2;
printf("%d",h[1]);

Array won't resize without copyOf()

You cannot resize an array in Java. Use ArrayList or LinkedList instead.

If you need to have a list for a primitive types and you don't want to wrap them into objects, take a look on Colt or Parallel Colt libraries.

How to increase an array's length

I would suggest you use an ArrayList as you won't have to worry about the length anymore. Once created, you can't modify an array size:

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed.

(Source)

How to decrease the size of an array after removing some elements from it

Also, you should just use if (numLength < (Array.length / 4)) rather then (1/4) * (Array.length); Don't do any weird casting or something like that. By default, java integer division will floor the result if that's the behavior you expect.

Also, you should be able to just use some Arrays.copyOfRange and System.arraycopy to achieve your copying needs.

https://docs.oracle.com/javase/7/docs/api/java/lang/System.html
https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html

Here's a simple code snippet that basically implement removing elements from arrays.

import java.lang.reflect.Array;
import java.util.Arrays;

public class MySpecialArray<T> {

T[] buf;

int size;

Class<T> type;

public MySpecialArray(Class<T> type, int initialBufSize) {
this.size = 0;
this.type = type;

buf = (T[]) Array.newInstance(type, initialBufSize);
}

/**
* Like arraylist add, it will basically add freely until it reaches the max length of the buffer.
* Then it has to expand the buffer. It uses buf.length * 2 + 1 to account for when an initialBufSize of 0 is
* supplied.
* @param elem
*/
public void add(T elem) {
if (this.size == this.buf.length) {
int newSize = this.buf.length * 2 + 1;
buf = Arrays.copyOf(buf, newSize);
}
this.buf[this.size] = elem;
this.size += 1;
}

public void add(T...elements) {
for(T elem : elements) {
this.add(elem);
}
}

/**
* Remove all occurrences of an element. Also reduce the max buf_size of the array if my utilized size is less than a fourth of my max buf size.
* @param removeMe element to remove all occurrences of
* @return
*/
public void remove(T removeMe) {
boolean found = false;
for(int i = 0; i < this.size; i++) {
if (buf[i].equals(removeMe)) {
System.arraycopy(buf, i+1, buf, i, this.size - i);
this.size -= 1;
if (this.size < this.buf.length / 4) {
this.buf = Arrays.copyOf(buf, this.buf.length / 2);
}
}
}
}

/**
* Remove the last element
* @return
*/
public T remove() {
if (this.size == 0) {
throw new RuntimeException("Cannot remove from empty buffer");
}
T removed = this.buf[this.size -1];
this.size -= 1;
if (this.size <= this.buf.length / 4) {
int newSize = this.buf.length / 2;
this.buf = Arrays.copyOf(this.buf, newSize);
}

return removed;
}

@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < this.size; i++) {
sb.append(this.buf[i].toString()).append(",");
}
return sb.toString();
}

public static void main(String...args) {
MySpecialArray<Integer> arr = new MySpecialArray(Integer.class, 50);
arr.add(10, 2, 4, 3, 5, 11, 9, 3, 8, 16);

System.out.println("===Pre removed===");
System.out.println(arr.buf.length);
System.out.println(arr.size);
System.out.println(arr);
arr.remove(3);

System.out.println("===After removing 3===");
System.out.println(arr.buf.length);
System.out.println(arr.size);
System.out.println(arr);
}
}

This sample, when just running it, will print out

===Pre removed===
50
10
10,2,4,3,5,11,9,3,8,16,
===After removing 3===
25
8
10,2,4,5,11,9,8,16,

Resizing a 2d array in java

This line

array[0] = x;

is not resizing the array array[0]; it's replacing the array array[0] such that array is now

12
000000
000000
000000
000000

The old array[0] is now discarded and it will be garbage collected. Now array[0] and x refer to the same array object, {1, 2}.



Related Topics



Leave a reply



Submit