How-To: Dynamic Arrays of Arbitrary Objects

Basic Tutorials concerning: GUI, Views, Activites, XML, Layouts, Intents, ...

How-To: Dynamic Arrays of Arbitrary Objects

Postby metachris » Fri Mar 06, 2009 9:21 pm

Hey guys!

This is a quick how-to on creating dynamic arrays because i couldn't find it around here yet. Sometimes it might be important and/or more flexible to save memory by not presetting the size of an array (sounds, images, videos, physics, ...).

This and more can be done very easy implementing a DynamicArray class, which holds the data array and extends it as needed. It can store any kind of objects and even mix different ones. Here is the basic code of the idea:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. import android.util.Log;
  2.  
  3.  
  4.  
  5. public class DynamicArray {
  6.  
  7.    private Object[] data;  
  8.  
  9.  
  10.  
  11.    public DynamicArray() {
  12.  
  13.       data = new Object[1];
  14.  
  15.    }
  16.  
  17.  
  18.  
  19.    public Object get(int position) {
  20.  
  21.       if (position >= data.length) {
  22.  
  23.          return 0;
  24.  
  25.       } else {
  26.  
  27.          return data[position];
  28.  
  29.       }
  30.  
  31.    }
  32.  
  33.  
  34.  
  35.    public void put(int position, Object value) {
  36.  
  37.            if (position >= data.length) {
  38.  
  39.                    int newSize = 2 * data.length;
  40.  
  41.                    if (position >= newSize)
  42.  
  43.                            newSize = 2 * position;
  44.  
  45.                    Object[] newData = new Object[newSize];
  46.  
  47.                    System.arraycopy(data, 0, newData, 0, data.length);
  48.  
  49.                    data = newData;
  50.  
  51.                    Log.v("x", "Size of dynamic array increased to " + newSize);
  52.  
  53.            }
  54.  
  55.            data[position] = value;
  56.  
  57.     }
  58.  
  59. }
Parsed in 0.033 seconds, using GeSHi 1.0.8.4


This working code shows the basic idea, and can be enhanced in various ways (for example by adding a function to get the last position, etc.)

We can use a dynamic array like this:
Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. /* Greate Array */
  2.  
  3. DynamicArray arr = new DynamicArray();
  4.  
  5.  
  6.  
  7. /* Add Integers and Strings */
  8.  
  9. arr.put(0, 123);
  10.  
  11. arr.put(1, "Hi There");
  12.  
  13.  
  14.  
  15. /* Output Array Content */
  16.  
  17. Log.v("Dynamic Array Test", "0: " + arr.get(0) + ", 1: " + arr.get(1));
Parsed in 0.032 seconds, using GeSHi 1.0.8.4


Happy hacking!
- Chris

This code was originally posted on 4feets.com
metachris
Junior Developer
Junior Developer
 
Posts: 24
Joined: Sat Feb 07, 2009 11:40 am

Top

Return to Novice Tutorials

Who is online

Users browsing this forum: No registered users and 2 guests