Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to resize arrays in Java

This tutorial will help you learn several techniques in resizing arays using Java.

The simplest dynamic array is constructed by allocating a fixed-size array and then dividing it into two parts: the first stores the elements of the dynamic array and the second is reserved, or unused. We can then add or remove elements at the end of the dynamic array in constant time by using the reserved space, until this space is completely consumed. The number of elements used by the dynamic array contents is its logical size or size, while the size of the underlying array is called the dynamic array's capacity, which is the maximum possible size without relocating data.

In applications where the logical size is bounded, the fixed-size data structure suffices. This may be short-sighted since problems with the array filling up turn up later. Resizing the underlying array is an expensive task, typically involving copying the entire contents of the array.

In Java Array cannot be resized once it is declared. But there is a hack or other way to do it. System class provides a utility method arrayCopy, it copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. Addingreflection to this functionality we can achieve it.

Listing 1: Resizing the array

private static Object resizeArray (Object array, int newSize) {
  int oldSize =
      java.lang.reflect.Array.getLength(array);
  Class elementType =
      array.getClass().getComponentType();
  Object newArray =
    java.lang.reflect.Array.newInstance(
      elementType, newSize);
  int preserveLength = Math.min(oldSize, newSize);
  if (preserveLength > 0)
    System.arraycopy(array, 0,
        newArray, 0, preserveLength);
  return newArray;
}

Let us see the alternate way to resized the array dynamically. If you want a dynamic data structure with random access, you use a Array (Map, ArrayList,...). If you need to expand, you can use System.arraycopy() method to copy the content of an array to another one. But a better way is to use a Vector or an ArrayList. ArrayList is roughly equivalent to Vector, except that it is unsynchronized.

Listing 2: Defining ArrayList Demo

import java.util.ArrayList;
 
public class ArrayListDemo {
  public static void main (String arg[]) {
    ArrayListDemo x = new ArrayListDemo();
    x.doit1();
    x.doit2();
  }
 
  public void doit1() {
    // single dimension
    ArrayList<String> list = new ArrayList<String>();
    list.add("a");
    list.add("b");
    int size = list.size();  // 2
    System.out.println("Array 1 " +list.get(0));   // a
  }
 
  public void doit2() {
    // multi dimensions
    ArrayList<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
    ArrayList<String> l1 = new ArrayList<String>();
    l1.add("a");
    ArrayList<String> l2 = new ArrayList<String>();
    l2.add("b");
    ArrayList<String> l3 = new ArrayList<String>();
    l3.add("c");
 
    list.add(l1);
    list.add(l2);
    list.add(l3);
 
    int size1 = list.size();  // 3
    int size2 = list.get(0).size();  // 1
    System.out.println("Array 2 " 
      + list.get(1).get(0));   // b
    }
}

The List interface offers an ArrayList and LinkedList concrete implementation.

Some of the array concrete implementations are subject to potential expensive resizing as the number of elements added to the Array grows such as ArrayList, Vector, HashMap, and ConcurrentHashMap since their underlying data store is an array. Other arrays such as LinkedList or TreeMap often use one or more object references between the elements stored to chain together the elements managed by the Array. The former of these, those that use an array for the Array's underlying data store, can be subject to performance issues when the underlying data store is resized due to the Array growing in the number of elements it holds. Although these Arrays classes have constructors that take an optional size argument, these constructors are often not used, or the size provided in an application program is not optimal for the Array's use.

It is possible that there exists concrete implementations of Java Arrays classes, such as LinkedList and TreeMap, that use arrays as underlying data storage. Those concrete implementations may also be subject to resizing. Collecting a heap profile and looking at array resizing will show which Java Arrays classes are resizing.

Two factors decide when the data storage for a HashMap is resized: the capacity of the data storage and the load factor. The capacity is the size of the underlying data storage. That's the HashMap.Entry[]'s size. And the load factor is a measure of how full the HashMap is allowed to reach before the HashMap's data storage, the Entry[], is resized. A HashMap resize results in a new Entry[] being allocated, twice as large as the previous Entry[], the entries in the Entry[] are rehashed and put in the Entry[]. The CPU instructions required to resize a HashMap are greater than what is required by StringBuilder or StringBuffer resizing due to the rehashing of the Entry[] elements.

In some cases an array can be declared with T[] a. Unfortunately, one cannot do a = new T[somethingBigger]. That is why, reflection needs to be used.

Listing 3: Using the reflection to resize the array

import java.lang.reflect.Array;

public class EnlargeArray<T> {
        /**
           * @param args The command line args
         */
        public static void main(String[] args) {
                Integer[] myArray = { 1, 2, 3, 4 };
                // Show original
                System.out.println(java.util.Arrays.toString(myArray));
                // Enlarge it twofold
                myArray = EnlargeArray.doubleSize(myArray);

                for(int i = 0;i < myArray.length;i++) {      
                    myArray[i] = i + 1;
                }

                System.out.println(java.util.Arrays.toString(myArray));
        }

        /**
         * Double the size of a array
         *
         * @param <T> The array element type
         * @param original The original array
         *
         * @return The new array, doubled in size
         */
public static <T> T[] doubleSize(T[] original) {
            T[] result = (T[]) Array.newInstance(original[0].getClass(), original.length * 2);
            System.arraycopy(original, 0, result, 0, original.length);
            return result;
        }
}

A built-in array instance : T[] is a fast, fixed-sized array. To resize such an array, you would need to create a second array of the new size and duplicate the items from the old array over. It may show up in the inspector as its content's type is known, but only if it is a serializable type.

Note that you can convert between built-in arrays and Arrays.If you start with an array and then convert it to an Array, change the Array and then convert back, you can shorthand the process, but this is hardly the most efficient route.

If you wanted a dynamically sized array-like structure that serializes in the inspector, you want a System.Collections.Generic List of a serializable type.

Use resize( ) to change the dimensions of an array, making it larger or smaller, or change the number of dimensions. To determine the number of dimensions, check the array’s dimensions property. The size property of the array reflects the number of elements.For a one-dimensional array, that’s all you need to know. For a two-dimensional array, you can’t determine the number of rows or columns from the size property alone (unless the size is one-a one-by-one array). To determine the number of columns or rows in a two-dimensional array, use the ALEN( ) function.

For a one-dimensional array, you can change the number of elements by calling resize( ) and specifying the number of elements as parameter. You can also set the size property of the array directly, which is a bit less typing.

You can also change a one-dimensional array into a two-dimensional array by specifying both a <rows expN> and a nonzero <cols expN> parameter. This makes the array the designated size.

For a two-dimensional array, you can specify a new number of rows or both row and column dimensions for the array. If you omit <cols expN>, the <rows expN> parameter sets the number of rows only. With both a <rows expN> and a nonzero <cols expN>, the array is changed to the designated size.

You can change a two-dimensional array to a one-dimensional array by specifying <cols expN> as zero and <rows expN> as the number of elements.

To change the number of columns only for a two-dimensional array, you will need to specify both the <rows expN> and <cols expN> parameters, which means that you have to determine the number of rows in the array, if not known, and specify it unchanged as the <rows expN> parameter.

To add a single row or column to an array, use the grow( ) method.

If you add or remove columns from the array, you can use to specify how you want existing elements to be placed in the new array. If <retain values expN> is zero or isn’t specified, resize( ) rearranges the elements, filling in the new rows or columns or adjusting for deleted elements, and adding or removing elements at the end of the array, as needed. This is shown below.

Figures displaying initial array and after resizing

Figure 1: Figures displaying initial array and after resizing

Conclusion

We saw various ways of resizing the java array including using the reflection method . Hope this will help you.



Software Developer from India. I hold Master in Computer Applications Degree and is well versed with programming languages such as Java, .Net, C and C++ and possess good working knowledge on Mobile Platforms as well.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login