Warning: Parameter 1 to Language::getMagic() expected to be a reference, value given in /home/wikija5/public_html/w/includes/StubObject.php on line 58

Warning: Parameter 3 to renderSEO() expected to be a reference, value given in /home/wikija5/public_html/w/includes/parser/Parser.php on line 3243
Resize an array using ArrayList - WikiJava
Saturday, 13th February 2016
Follow WikiJava on twitter now. @Wikijava

Resize an array using ArrayList

From WikiJava

Jump to: navigation, search

This example shows how to use an ArrayList to get a dynamic size array.


the article

Arrays cannot be resized dynamically. If you want a dynamic data structure with random access, you use a Collection (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.


import java.util.ArrayList;
public class ArrayListDemo {
  public static void main (String arg[]) {
    ArrayListDemo x = new ArrayListDemo();
  public void doit1() {
    // single dimension
    ArrayList<String> list = new ArrayList<String>();
    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>();
    ArrayList<String> l2 = new ArrayList<String>();
    ArrayList<String> l3 = new ArrayList<String>();
    int size1 = list.size();  // 3
    int size2 = list.get(0).size();  // 1
    System.out.println("Array 2 " 
      + list.get(1).get(0));   // b

See Also

Resize an array, Real's Java How To

Comments from the users

To be notified via mail on the updates of this discussion you can login and click on watch at the top of the page

Comments on wikijava are disabled now, cause excessive spam.