Dynamic Array resizing

I have a class with some data members in it. Data for the objects comes frm a XML file. I have to parse out the xml file and create objects. Before reading the XML file i dunno as to how many objects i need to create. I wud like to know a way where I can dynamically increase the size of the object array as I read through the XMl file.
Thanks in advance,
Kris.

This is the source:
* @(#)ArrayList.java     1.36 01/12/03
* Copyright 2002 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
package java.util;
* Resizable-array implementation of the <tt>List</tt> interface.  Implements
* all optional list operations, and permits all elements, including
* <tt>null</tt>.  In addition to implementing the <tt>List</tt> interface,
* this class provides methods to manipulate the size of the array that is
* used internally to store the list.  (This class is roughly equivalent to
* <tt>Vector</tt>, except that it is unsynchronized.)<p>
* The <tt>size</tt>, <tt>isEmpty</tt>, <tt>get</tt>, <tt>set</tt>,
* <tt>iterator</tt>, and <tt>listIterator</tt> operations run in constant
* time.  The <tt>add</tt> operation runs in <i>amortized constant time</i>,
* that is, adding n elements requires O(n) time.  All of the other operations
* run in linear time (roughly speaking).  The constant factor is low compared
* to that for the <tt>LinkedList</tt> implementation.<p>
* Each <tt>ArrayList</tt> instance has a <i>capacity</i>.  The capacity is
* the size of the array used to store the elements in the list.  It is always
* at least as large as the list size.  As elements are added an ArrayList,
* its capacity grows automatically.  The details of the growth policy are not
* specified beyond the fact that adding an element has constant amortized
* time cost.<p>
* An application can increase the capacity of an <tt>ArrayList</tt> instance
* before adding a large number of elements using the <tt>ensureCapacity</tt>
* operation.  This may reduce the amount of incremental reallocation.<p>
* <strong>Note that this implementation is not synchronized.</strong> If
* multiple threads access an <tt>ArrayList</tt> instance concurrently, and at
* least one of the threads modifies the list structurally, it <i>must</i> be
* synchronized externally.  (A structural modification is any operation that
* adds or deletes one or more elements, or explicitly resizes the backing
* array; merely setting the value of an element is not a structural
* modification.)  This is typically accomplished by synchronizing on some
* object that naturally encapsulates the list.  If no such object exists, the
* list should be "wrapped" using the <tt>Collections.synchronizedList</tt>
* method.  This is best done at creation time, to prevent accidental
* unsynchronized access to the list:
* <pre>
*     List list = Collections.synchronizedList(new ArrayList(...));
* </pre><p>
* The iterators returned by this class's <tt>iterator</tt> and
* <tt>listIterator</tt> methods are <i>fail-fast</i>: if list is structurally
* modified at any time after the iterator is created, in any way except
* through the iterator's own remove or add methods, the iterator will throw a
* ConcurrentModificationException.  Thus, in the face of concurrent
* modification, the iterator fails quickly and cleanly, rather than risking
* arbitrary, non-deterministic behavior at an undetermined time in the
* future.
* <p>Note that the fail-fast behavior of an iterator cannot be guaranteed
* as it is, generally speaking, impossible to make any hard guarantees in the
* presence of unsynchronized concurrent modification.  Fail-fast iterators
* throw <tt>ConcurrentModificationException</tt> on a best-effort basis.
* Therefore, it would be wrong to write a program that depended on this
* exception for its correctness: <i>the fail-fast behavior of iterators
* should be used only to detect bugs.</i>
* @author  Josh Bloch
* @version 1.36, 12/03/01
* @see         Collection
* @see         List
* @see         LinkedList
* @see         Vector
* @see         Collections#synchronizedList(List)
* @since   1.2
public class ArrayList extends AbstractList
        implements List, RandomAccess, Cloneable, java.io.Serializable
    private static final long serialVersionUID = 8683452581122892189L;
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer.
    private transient Object elementData[];
     * The size of the ArrayList (the number of elements it contains).
     * @serial
    private int size;
     * Constructs an empty list with the specified initial capacity.
     * @param   initialCapacity   the initial capacity of the list.
     * @exception IllegalArgumentException if the specified initial capacity
     *            is negative
    public ArrayList(int initialCapacity) {
     super();
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
     this.elementData = new Object[initialCapacity];
     * Constructs an empty list with an initial capacity of ten.
    public ArrayList() {
     this(10);
     * Constructs a list containing the elements of the specified
     * collection, in the order they are returned by the collection's
     * iterator.  The <tt>ArrayList</tt> instance has an initial capacity of
     * 110% the size of the specified collection.
     * @param c the collection whose elements are to be placed into this list.
     * @throws NullPointerException if the specified collection is null.
    public ArrayList(Collection c) {
        size = c.size();
        // Allow 10% room for growth
        elementData = new Object[
                      (int)Math.min((size*110L)/100,Integer.MAX_VALUE)];
        c.toArray(elementData);
     * Trims the capacity of this <tt>ArrayList</tt> instance to be the
     * list's current size.  An application can use this operation to minimize
     * the storage of an <tt>ArrayList</tt> instance.
    public void trimToSize() {
     modCount++;
     int oldCapacity = elementData.length;
     if (size < oldCapacity) {
         Object oldData[] = elementData;
         elementData = new Object[size];
         System.arraycopy(oldData, 0, elementData, 0, size);
     * Increases the capacity of this <tt>ArrayList</tt> instance, if
     * necessary, to ensure  that it can hold at least the number of elements
     * specified by the minimum capacity argument.
     * @param   minCapacity   the desired minimum capacity.
    public void ensureCapacity(int minCapacity) {
     modCount++;
     int oldCapacity = elementData.length;
     if (minCapacity > oldCapacity) {
         Object oldData[] = elementData;
         int newCapacity = (oldCapacity * 3)/2 + 1;
             if (newCapacity < minCapacity)
          newCapacity = minCapacity;
         elementData = new Object[newCapacity];
         System.arraycopy(oldData, 0, elementData, 0, size);
     * Returns the number of elements in this list.
     * @return  the number of elements in this list.
    public int size() {
     return size;
     * Tests if this list has no elements.
     * @return  <tt>true</tt> if this list has no elements;
     *          <tt>false</tt> otherwise.
    public boolean isEmpty() {
     return size == 0;
     * Returns <tt>true</tt> if this list contains the specified element.
     * @param elem element whose presence in this List is to be tested.
     * @return  <code>true</code> if the specified element is present;
     *          <code>false</code> otherwise.
    public boolean contains(Object elem) {
     return indexOf(elem) >= 0;
     * Searches for the first occurence of the given argument, testing
     * for equality using the <tt>equals</tt> method.
     * @param   elem   an object.
     * @return  the index of the first occurrence of the argument in this
     *          list; returns <tt>-1</tt> if the object is not found.
     * @see     Object#equals(Object)
    public int indexOf(Object elem) {
     if (elem == null) {
         for (int i = 0; i < size; i++)
          if (elementData==null)
          return i;
     } else {
     for (int i = 0; i < size; i++)
          if (elem.equals(elementData[i]))
          return i;
     return -1;
* Returns the index of the last occurrence of the specified object in
* this list.
* @param elem the desired element.
* @return the index of the last occurrence of the specified object in
* this list; returns -1 if the object is not found.
public int lastIndexOf(Object elem) {
     if (elem == null) {
     for (int i = size-1; i >= 0; i--)
          if (elementData[i]==null)
          return i;
     } else {
     for (int i = size-1; i >= 0; i--)
          if (elem.equals(elementData[i]))
          return i;
     return -1;
* Returns a shallow copy of this <tt>ArrayList</tt> instance. (The
* elements themselves are not copied.)
* @return a clone of this <tt>ArrayList</tt> instance.
public Object clone() {
     try {
     ArrayList v = (ArrayList)super.clone();
     v.elementData = new Object[size];
     System.arraycopy(elementData, 0, v.elementData, 0, size);
     v.modCount = 0;
     return v;
     } catch (CloneNotSupportedException e) {
     // this shouldn't happen, since we are Cloneable
     throw new InternalError();
* Returns an array containing all of the elements in this list
* in the correct order.
* @return an array containing all of the elements in this list
*      in the correct order.
public Object[] toArray() {
     Object[] result = new Object[size];
     System.arraycopy(elementData, 0, result, 0, size);
     return result;
* Returns an array containing all of the elements in this list in the
* correct order; the runtime type of the returned array is that of the
* specified array. If the list fits in the specified array, it is
* returned therein. Otherwise, a new array is allocated with the runtime
* type of the specified array and the size of this list.<p>
* If the list fits in the specified array with room to spare (i.e., the
* array has more elements than the list), the element in the array
* immediately following the end of the collection is set to
* <tt>null</tt>. This is useful in determining the length of the list
* <i>only</i> if the caller knows that the list does not contain any
* <tt>null</tt> elements.
* @param a the array into which the elements of the list are to
*          be stored, if it is big enough; otherwise, a new array of the
*           same runtime type is allocated for this purpose.
* @return an array containing the elements of the list.
* @throws ArrayStoreException if the runtime type of a is not a supertype
* of the runtime type of every element in this list.
public Object[] toArray(Object a[]) {
if (a.length < size)
a = (Object[])java.lang.reflect.Array.newInstance(
a.getClass().getComponentType(), size);
     System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
// Positional Access Operations
* Returns the element at the specified position in this list.
* @param index index of element to return.
* @return the element at the specified position in this list.
* @throws IndexOutOfBoundsException if index is out of range <tt>(index
*           < 0 || index >= size())</tt>.
public Object get(int index) {
     RangeCheck(index);
     return elementData[index];
* Replaces the element at the specified position in this list with
* the specified element.
* @param index index of element to replace.
* @param element element to be stored at the specified position.
* @return the element previously at the specified position.
* @throws IndexOutOfBoundsException if index out of range
*          <tt>(index < 0 || index >= size())</tt>.
public Object set(int index, Object element) {
     RangeCheck(index);
     Object oldValue = elementData[index];
     elementData[index] = element;
     return oldValue;
* Appends the specified element to the end of this list.
* @param o element to be appended to this list.
* @return <tt>true</tt> (as per the general contract of Collection.add).
public boolean add(Object o) {
     ensureCapacity(size + 1); // Increments modCount!!
     elementData[size++] = o;
     return true;
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
* @param index index at which the specified element is to be inserted.
* @param element element to be inserted.
* @throws IndexOutOfBoundsException if index is out of range
*          <tt>(index < 0 || index > size())</tt>.
public void add(int index, Object element) {
     if (index > size || index < 0)
     throw new IndexOutOfBoundsException(
          "Index: "+index+", Size: "+size);
     ensureCapacity(size+1); // Increments modCount!!
     System.arraycopy(elementData, index, elementData, index + 1,
               size - index);
     elementData[index] = element;
     size++;
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
* @param index the index of the element to removed.
* @return the element that was removed from the list.
* @throws IndexOutOfBoundsException if index out of range <tt>(index
*           < 0 || index >= size())</tt>.
public Object remove(int index) {
     RangeCheck(index);
     modCount++;
     Object oldValue = elementData[index];
     int numMoved = size - index - 1;
     if (numMoved > 0)
     System.arraycopy(elementData, index+1, elementData, index,
               numMoved);
     elementData[--size] = null; // Let gc do its work
     return oldValue;
* Removes all of the elements from this list. The list will
* be empty after this call returns.
public void clear() {
     modCount++;
     // Let gc do its work
     for (int i = 0; i < size; i++)
     elementData[i] = null;
     size = 0;
* Appends all of the elements in the specified Collection to the end of
* this list, in the order that they are returned by the
* specified Collection's Iterator. The behavior of this operation is
* undefined if the specified Collection is modified while the operation
* is in progress. (This implies that the behavior of this call is
* undefined if the specified Collection is this list, and this
* list is nonempty.)
* @param c the elements to be inserted into this list.
* @return <tt>true</tt> if this list changed as a result of the call.
* @throws IndexOutOfBoundsException if index out of range <tt>(index
*          < 0 || index > size())</tt>.
* @throws NullPointerException if the specified collection is null.
public boolean addAll(Collection c) {
     modCount++;
     int numNew = c.size();
     ensureCapacity(size + numNew);
     Iterator e = c.iterator();
     for (int i=0; i<numNew; i++)
     elementData[size++] = e.next();
     return numNew != 0;
* Inserts all of the elements in the specified Collection into this
* list, starting at the specified position. Shifts the element
* currently at that position (if any) and any subsequent elements to
* the right (increases their indices). The new elements will appear
* in the list in the order that they are returned by the
* specified Collection's iterator.
* @param index index at which to insert first element
*          from the specified collection.
* @param c elements to be inserted into this list.
* @return <tt>true</tt> if this list changed as a result of the call.
* @throws IndexOutOfBoundsException if index out of range <tt>(index
*          < 0 || index > size())</tt>.
* @throws NullPointerException if the specified Collection is null.
public boolean addAll(int index, Collection c) {
     if (index > size || index < 0)
     throw new IndexOutOfBoundsException(
          "Index: "+index+", Size: "+size);
     int numNew = c.size();
     ensureCapacity(size + numNew); // Increments modCount!!
     int numMoved = size - index;
     if (numMoved > 0)
     System.arraycopy(elementData, index, elementData, index + numNew,
               numMoved);
     Iterator e = c.iterator();
     for (int i=0; i<numNew; i++)
     elementData[index++] = e.next();
     size += numNew;
     return numNew != 0;
* Removes from this List all of the elements whose index is between
* fromIndex, inclusive and toIndex, exclusive. Shifts any succeeding
* elements to the left (reduces their index).
* This call shortens the list by <tt>(toIndex - fromIndex)</tt> elements.
* (If <tt>toIndex==fromIndex</tt>, this operation has no effect.)
* @param fromIndex index of first element to be removed.
* @param toIndex index after last element to be removed.
protected void removeRange(int fromIndex, int toIndex) {
     modCount++;
     int numMoved = size - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
     // Let gc do its work
     int newSize = size - (toIndex-fromIndex);
     while (size != newSize)
     elementData[--size] = null;
* Check if the given index is in range. If not, throw an appropriate
* runtime exception.
private void RangeCheck(int index) {
     if (index >= size || index < 0)
     throw new IndexOutOfBoundsException(
          "Index: "+index+", Size: "+size);
* Save the state of the <tt>ArrayList</tt> instance to a stream (that
* is, serialize it).
* @serialData The length of the array backing the <tt>ArrayList</tt>
* instance is emitted (int), followed by all of its elements
* (each an <tt>Object</tt>) in the proper order.
private synchronized void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException{
     // Write out element count, and any hidden stuff
     s.defaultWriteObject();
// Write out array length
s.writeInt(elementData.length);
     // Write out all elements in the proper order.
     for (int i=0; i<size; i++)
s.writeObject(elementData[i]);
* Reconstitute the <tt>ArrayList</tt> instance from a stream (that is,
* deserialize it).
private synchronized void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
     // Read in size, and any hidden stuff
     s.defaultReadObject();
// Read in array length and allocate array
int arrayLength = s.readInt();
elementData = new Object[arrayLength];
     // Read in all elements in the proper order.
     for (int i=0; i<size; i++)
elementData[i] = s.readObject();

Similar Messages

  • Populating a dynamic array with objects and managing it in runtime.

    So I'm another stuck firstyear. I'll try and make my question compact. I'm using Flash CS6 and have drawn an animated character on the stage that consists of separate parts that are animated and its head is a separate class/symbol entirely because it has not only animation, but a state switch timeline as well. This said Head extends the Main that is the character MovieClip.
    I am using a dynamic array to store and .push and .splice objects of another class that would collide with this said Head.
    I also discovered the super() function that is implicitly called as the constructor of the parent in any child class that extends the parent, in this case Head extends Main. The issue is that my collidable object array is populated within the main, within the function that spawns every next collidable object with a TimerEvent. This said function then gets called twice due to the super() call.
    I have tried putting this super() call into an impossible statement in my child class, but it doesn't change a thing, and it was said that this method is unsafe so I don't even know if it should be working.
    However what confuses me the most is when I trace() the .length of my collidable object array at the end of that function. As I said earlier, the original function both spawns an object after a period of Timer(1000) and adds it to the stage as well as adds the object onto the object array, but the super() constructor only duplicates the length call and a creates a copy of the object on the stage, but it does not add the second copy of the object onto the array. The trace() output goes on like so:
    1
    1
    2
    2
    3
    3
    4
    4
    etc.
    I wonder why and I'm really stumped by this.
    Here is the code in question:
    public class Main extends MovieClip {
                        public var nicesnowflake: fallingsnow;
                        var nicesnowflakespawntimer: Timer = new Timer(1000);
                        public var nicesnowflakearray: Array = new Array();
                        public function Main() {
                                  nicesnowflakespawntimer.addEventListener(TimerEvent.TIMER, nicesnowflakespawn);
                                  nicesnowflakespawntimer.start();
                        public function nicesnowflakespawn(event:TimerEvent) : void {
                                  nicesnowflake = new fallingsnow;
                                  nicesnowflake.x = Math.random()* stage.stageWidth;
                                  nicesnowflake.y = - stage.stageHeight + 100;
                                  nicesnowflakearray.push(nicesnowflake);
                                  stage.addChild(nicesnowflake);
                                  trace(nicesnowflakearray.length);
                                  for (var i:Number = 0; i < nicesnowflakearray.length; i++){
                                            nicesnowflakearray[i].addEventListener(Event.ENTER_FRAME, snowhit);
                        public function snowhit(event:Event) : void {
                                  if (nicesnowflakearray[0].y >= 460){
                                            if (nicesnowflakearray[0].y == stage.stageHeight) {
                                            nicesnowflakearray.splice(nicesnowflakearray.indexOf(nicesnowflake), 1);
                                  //if (this.hitTestObject(nicesnowflake)){
                                            //trace("hit");
    I am also fiddling with the collision, but I believe that it would sort itself out when I deal with the array pop and depop properly. However I'm pasting it anyway in case the issue is subtly hidden somewhere I'm not looking for it. And here is the child class:
    public class Head extends Main {
                        public function Head(){
                                  if (false){
                                            super();
                                  this.stop();
    So like what happens at the moment is that the array gets populated by the first object that spawns, but there is two objects on the stage, then when the objects reach stage.460y mark the array splices() the one object away and displays an error:
    "#1010: A term is undefined and has no properties.
              at Main/snowhit()"
    then when the next object spawns, it repeats the process. Why does it trace the array.length as "1, 1, 2, 2, 3, 3, 4, 4, 5, 5, etc" until the despawn point and then goes on to display an error and then starts from 1 again, because if the array length is more than one object at the time when the first object of the array gets spliced away, shouldn't it go on as usual, since there are other objects in the array?
    Thank you very much to whomever will read this through.

    There are multiple problems:
    1. You should add eventlisteners for your objects only once, but you add eventlisteners every time your timer runs to all of your snowflakes, again and again:
                                  for (var i:Number = 0; i < nicesnowflakearray.length; i++){
                                            nicesnowflakearray[i].addEventListener(Event.ENTER_FRAME, snowhit);
    change it to
    nicesnowflake.addEventListener(Event.ENTER_FRAME, snowhit);
    I don`t see why its even necessary to employ this snowflakearray, it would be much straight forward if you simply let the snowflakes take care of themselves.
    2. Then you have to change your enterframe function accordingly
    public function snowhit(event:Event) : void {
                                  if (e.currentTarget.y >= 460){
                                            if (e.currentTarget.y == stage.stageHeight) {
                                            e.currentTarget.removeEventlistener(Event.ENTER_FRAME, snowhit);
                                            removeChild(e.currentTarget);
    3.
                                  //if (this.hitTestObject(nicesnowflake)){
                                            //trace("hit");
    since "this" is a reference to the Main class (root) it surely won`t function as you intend it to.
                                  if (false){
                                            super();
    makes no sense to use a condition that can never be true

  • Dynamic array

    how to implement dynamic array size in java...??
    say if i want to add the element in an array then how should i do it..??

    For dynamic array...Vector is the best one i
    est one i think....
    Sigh. Unless other code requires it (for example, JTable's DefaultTableModel),
    Arraylist is preferred over the legacy class Vector.
    And even then I wouldn't recommend ArrayList as the "best" list. What if the OP
    wanted to have a FIFO queue? Would you recommend ArrayList/Vector over
    LinkedList?

  • Creating a dynamic Array

    Thanks for reply.
    I want to create a dynamic array and for this I used ArrayList Collection and Vector Class. I am using JDK 1.4.1 . But , I have a problem in that. In ArrayList, I used the following code:
    ArrayList al = new ArrayList();
    while(rs.next())
    al.add(rs.getString("Enter_Year"));
    al.add(rs.getString("UG_Production_Mi_Te"));
    al.add(rs.getString("OC_Production_Mi_Te"));
    al.add(rs.getString("Total_Production_Mi_Te"));
    al.add(rs.getString("OBR_MM3"));
    al.add(rs.getString("OMS_Te"));
    al.add(rs.getString("Coal_Offtake_Mi_Te"));
    al.add(rs.getString("Supply_to_Steel_Plant_Th_Te"));
    al.add(rs.getString("Royalty_SalesTax_MP_Crs"));
    al.add(rs.getString("Royalty_SalesTax_CG_Crs"));
    al.add(rs.getString("Total_ManPower"));
    al.add(rs.getString("Fatality_Rate_per_Mi_Te_Output"));
    al.add(rs.getString("Total_Wellfare_Expenditure_Crs"));
    String rpt[][] = new String[al.size()][];
    rpt = al.toArray(rpt); // ArrayStoreExecption error
    String colheads[] = {"...........My Table's Column names are here....."};
    JTable table = new JTable(rpt,colheads);
    JScrollPane jsp = new JScrollPane(table);
    add(jsp);
    At the statement having comment line I received the error ArrayStoreException. The JTable accepts the 2 D array for storing the info and I think the toArray() method is not working there and can't convert the ArrayList elements into an Array. Similarily, Vector Class is also not converting the elements into an array object and showing the same error only.
    Please help me to convert it into an array object so that I can pass it into the JTable argument.

    That isn't a jdbc problem but rather a collection problem.
    You certainly can't convert a one dimensional collection into a two dimensional array automatically. And that is what you are creating with the while loop.
    Since you know the column names you also know the inner array size so you can start by creating a statically sized string array (not collection) in the loop and add that to the outer collection. That might solve the problem.

  • How to plot XY graph from 2 input of dynamic array ? ...

    I have 2 problem when I plot XY graph with 2 dynamic array :
    - I want to make the graph look like sweep chart. But it's seem not possible to use waveform graph?
    - The graph shoul move from left to right , then right to left, then left to right,.....
    Any one can give me some hints?  Thanks alot.
    Attachments:
    U1.PNG ‏21 KB
    XY radom value input.vi ‏147 KB

    I have to make Y change  from 0-10, then 10-0,.... Any one can help me to make it better?
    - How I shift the graph?
    Attachments:
    working_increse_decrease.vi ‏20 KB

  • Creating dynamic array

    Can anybody tell me how to create a dynamic array in Java??I dont want to fix size of array,it should take any number of values at runtime.Please tell me the syntax of using dynamic arrays.

    Hi,
    For creating an array of similar data elements, use
    ArrayList., but for storing elements which are in the
    form of object then use Vector...
    Best of Luck..
    R SWrong... the main different between ArrayList and Vector is that Vector was sychronized and ArrayList are not.

  • How can i maintain a dynamic array

    I want to maintain an dynamic array in my code . It shoud grow accroding to no of user inputs . 1 can entre 5 numbers and other 10 , then array size should grow orderly 5 and 10 like that . Array is int array.

    Read up on the Collections API. There is a tutorial on this site. At first blush, you want a List. If it will grow and you will not be removing and inserting constantly from the 'middle' of the list of items, then ArrayList is a logical choice as your List. Otherwise, use LinkedList. But definitely bone up on the tutorial. Understanding how Collections work is fundamental to any Java programming you will do.
    - Saish

  • Creating a dynamic array in Actionscript

    I am wondering how I would create a dynamic array in Acionscript, i.e. one that utilizes fields for mapping data like this:
    public var SMITH:Array = [
               {date:"29-Aug-05", close:45.87, profit:52},
               {date:"23-Aug-05", close:45.74, profit:32},
               {date:"21-Aug-05", close:45.77, profit:22},
               {date:"25-Aug-05", close:46.06, profit:51},
    but where you would just be reading in data without knowing what your data looks like.  In other words, I'd like to take something like a database table with X number of columns and have Actionsctipt map each row to an item in my array.  Something like this:
    for each row in table
    add {col1:value, col2:value, col3:value, ... colX:value} to Array
    So I won't know "date" or "close" or whatever at runtime, I'll just have X number of items for each element in the array. How would this be done?
    The reason I need this mapping feature is because I then want to map the table-like array as the data provider to charts, datagrids, etc.
    Thanks.

    If this post answers your question or helps, please mark it as such.
    You can download the lib for JSON in Flex here:
    http://code.google.com/p/as3corelib/downloads/list
    These pages describe using JSON and Flex, and databases:
    http://www.switchonthecode.com/tutorials/flex-php-tutorial-transmitting-data-using-json
    http://www.switchonthecode.com/tutorials/using-flex-php-and-json-to-modify-a-mysql-databas e
    http://www.switchonthecode.com/tutorials/flex-php-json-mysql-advanced-updating
    http://www.mikechambers.com/blog/2006/03/28/tutorial-using-json-with-flex-2-and-actionscri pt-3/

  • Store int values into dynamic array

    Hello all,
    I'm a newbie in JAVA whose want to store int values (coming from a resultset) into an dynamic array. I know that normally to create a "dynamic array" you'd better use a Vector, but it seems that I don't know how to use it correctly (throws me a exception as : Incompatible type for method. Can't convert int[] to java.lang.Object[]).
    Thanks in advance
    STF

    I want to use the copyInto method of the vector, but it throw me an exception as ')' expected
    I include a snip of my code below ;
    Vector v= new Vector();
    Vector vv=new Vector();
    String[] labels=new String[v.size()];
    Integer[] values=new Integer[vv.size()];
    cont=rs.getInt("COUNT(CASE_ID_)");
    vv.add(j,new Integer(cont));
    log=rs.getString("ORIG_SUBMITTER");
    v.add(j,new String(log));
    v.copyInto(String[] labels);
    vv.copyInto(Integer[] values);

  • Multidimensional dynamic arrays?

    Is there already (jdk 1.5) a dynamic array object for multiple dimensions? There is a dynamic ArrayList for 1-dimensional arrays. For multidemsional arrays, I just put ArrayList into ArrayList into ... as a workaround. But the retrievel of elements is rather clumsy - I would like to have something like MultiArrayList and get the element from a 2-dimensional MultiArrayList like
    myMultiArrayList.get(x, y);
    I havent' found such an object so far in the 1.5 javadocs. Is there any?

    Well, I'm thinking of something like
    MultiArrayList mal = new MultiArrayList(2); //2 = 2
    dimensions
    mal.set(value1, 0, 0); //set value1 at [0,0]Would you have one array of length 1 after that?
    And if I call, set(value, 100,100), do I end up with 100 arrays of length 100?
    What if I do this?
    MultiArrayList mal = new MultiArrayList(2);
    mal.set(value1, 0, 100);What do the arrays look like after that. Your idea seems very reasonable but you have specified how they will behave dynamically. I can think of several different ways off the top of my head.

  • Deleting dynamic arrays

    My main concern is worrying about having a memory leak due to a program crashing before it has the chance to reach the line of code in which technically releases its memory. What I do not understand is, if the program does crashes before it can release the memory of any dynamic arrays, wouldn't the memory leak still exist the next time you run the program and causing the leak to get worse each time?
    for example, if I had something like this...
    int main()
    int *a = new int[10];
    bool game = true;
    // then for some reason the program crashes somewhere along these lines...
    while(game) {
    do some code in which some reason cause the program to crash
    delete [] a;
    return 0;
    here in the example, if the program had crashed inside the while loop, wouldn't I have a memory leak which exist forever?

    BnTheMan wrote:
    The first instance is I wanted to know after reading some topics on the internet, I have heard that is is not a good Idea to set a pointer to know inside of a constructer class like this...
    should you do this, or does it depend on the compiler that you use, and what about if you are using XCode?
    Did you mean to type "not a good Idea to set a pointer to NULL"? That is what you code seems to say.
    They key part is memory management. People have been screwing that up for decades. You should initialize pointers to NULL or 0 (same thing) before using them. Then, when you are done with them, if they aren't NULL, you must release them. Even if you haven't allocated a pointer, you can always release it if it is NULL using free(), delete, or release - depending on what language you are using.
    If you allocate a pointer, then release its memory, you should re-set it back to NULL immediately if there is any chance that some other bit of code could try to release the memory. If you try to free a pointer twice, your app will crash.
    All this is true in any environment that doesn't have garbage collection. Don't think that garbage collection is the panacea it is made out to be. It is better to be able to manage your own memory when you need to. Plus, there are more system resources than just memory.
    2. The next thing I noticed was that it did not have any memory releasing code for when there is a problem with reading the file, such as if the file could not be opened. So I am wondering if something was to happen when opening the second MD2 file, in that it could not open the file because it was currupted, and I did something like this...
    MD2_Object::loadObject() {
    ifstream inFile;
    char buffer[64];
    inFile.open(myFile, istream::binary);
    if(!inFile) {
    ... the code I need to my question
    How can I tell the program that there was an error and that it needs to release the memory from the first dynamic array variable?
    (I added some { code } statements to format your code nicely. Reply to this post to see how I did it.)
    That is a good question, with several caveats. In your example, you are actually using static variables, not dynamic. All of your data is allocated on the stack. You didn't use any sort of malloc(), new, alloc, etc. Therefore, memory management is easy. When the current scope ends (usually the code between braces) anything allocated on the stack automatically goes away cleanly. Plus, since the stack is much more low level than dynamic memory, you can do stack allocations much more quickly.
    But, had used dynamic allocation, this would be an issue. It is a significant problem that is rarely handled correctly. If there is an error, you need to release any resources (such as memory) that you have allocated. There are a number of ways to handle this, depending on your language and how you want to do it.
    The first solution is to exploit the fact that, in C++, you can declare your variables anywhere you want. They don't have to be at the beginning of the scope. The best thing to do is don't allocate resources unless you know you can use them. If you fail halfway through, you would have to release all resources that you had allocated up to that point.
    Some other ideas are to use exceptions and wrap allocations in classes such as auto_ptr. Then, when you encounter an error, you throw and exception and you use the stack scoping rules, though static wrapper variables, to release dynamic data underneath.
    Yeah, it gets complicated. Maybe most more code that precisely shows what you are concerned with. Wrap your code between two lines of
    { code }
    { code }
    without the spaces and it will print out nicely. So far, it looks like you are doing everything correctly. Sometimes, instead of asking how to do something, you'll get better responses by just posting how you do it and, if there are any problems, people will pick it apart Harsh, but effective.

  • Dynamic arrays

    Hi all,
    I am controlling a two level stepper motor via  a USB 6009. I created the pulses using software timing by setting an array of elements to change between 0 and 5 V continuously as shown in the attachement. The probelm now is that i want to be able to control the number of degrees that the motor moves by so say 1 degree = 35 elements in the array. How do I do that using dynamic arrays? i'd like to be able to specify the number of degrees and hence the number of elements in the array of values 0 and 5. I am completely new to labView so any ideas or examples will be great.
    Thank you
    Myriam
    Attachments:
    PulseMotSelect.vi ‏79 KB

    Thank you very much for your prompt answer. I thought the built in signal generation functions require a clock and the USB does not have a clock on it. That is why I am using software timing. If it is still possibel to use the buillt in signal generation functions then where do i get them from on Labview if i want to create a square pulse? and yes i did create them all by hand becuase i didnt know where these functions are and if they would work with USB 6009 without the clock.
    With the code that I have sent you, the motor moves continuously once the usb is connected. The only way i can stop it is if i unplug the USB.  What i want to be able to do is to be able to conrol the motor so that it stops after a certain number of degrees specified by the user. This is what i wanted the dynamic array for. Another way that i thought of for doing that is using a timed loop to control the motor motion instead. So say it takes 1 sec to move 1 degree then 30 secs to move one degree and use that to control the degree of motion rather than the elements in the array. Would that still work? if not then how can i modify the array to do that? as it moves continuously with 1500 elements so how can i limit when it stops?
    Sorry if my problem is too complicated but i am new to labview so any help is welcome.
    Thank you in advnace for your help
    Myriam

  • Linklist and dynamic array in java?

    how to define linklist object and to build dynamic array in java?

    with so little information, all one can do is pointing you to :
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/LinkedList.html
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/ArrayList.html

  • About dynamic array

    Which one does Java support ?
    Fixed heap-dynamic array or heap-dynamic array.
    I'm so confused ~.~

    so, does it mean that java support both fixed heap
    dynamic array and heap dynamic array?Java supports both static (fixed length) arrays and dynamic (variable length) arrays. The static arrays belong to the core language. The dynamic array implementation, called ArrayList, is part of a standard library, called the Collections Framework. In both cases they're used as objects and thus stored on the heap (it's currently not possible to allocate an object on the stack).

  • Dynamic array gen....

    Hello All,
    We are facing some problem regarding generating array dynamically.
    Is it possible to generate array dynamically within program in java.
    We want to genrate an array, of type byte as shown below.
    byte datafile1[],datafile2[],datafile3[],datafile4[]; etc.,
    We want to decleare and initalize these arrays dynamically within the program(not manually).
    Hope you all understand my problem.
    Help me to solve this problem as soon as posible.
    Its urgent for me.
    Thankyou,
    RajivChowdary.

    Either use an array-like object, such as an instance of any List types (Vector or ArrayList, for instance) as they will dynamically resize when you add or remove elements from them, or create a method to "resize" your array at runtime. Since arrays cannot be resized per se, simply create a new array of the size that you'd like, and copy the contents of the old one into it using System.arrayCopy(). I'd personally go for the List object.

Maybe you are looking for

  • Invoice output not coming properly

    Dear Experts, I have maintained condition record for the billing type and assigned it to the printer. Some of the invoices output are coming properly but for 4 to 5 invoices, print out prview is just skipping and when I click for printing, the system

  • Function used in view definition is called multiple times

    I am trying to write a view that boils down to the following statement: SELECT val, val FROM ( SELECT SYS_GUID() val FROM dual Against my expectation, this calls SYS_GUID() twice, resulting in two different values for val. I've written it here as inl

  • ITMS previews won't play on iPad

    When I launch the iTMS on my iPad, I can't get any music to preview.  it flashes momentarily, then stops.  Same thing with a movie.  If I click the trailer image, the screen shifts momentarily to the video player, then shifts back to iTMS.  I've trie

  • MIDets and their classes

    Hi, I'll say from the outset I'm not expecting a detailed answer, just some reasurence that what i ask is possible. I'm trying to write a program that uses a combination of form and canvas classes inparticular where the canvas classes are not embedde

  • How to gray out fields in VA01 & VA02

    Hi All, My requirement is to restrict manual entries of line items. While creating a  credit memo with refrence to billing document the items from billing document gets copied to this document. User wants to restrict entering more line items apart fr