Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / June 2007

Tip: Looking for answers? Try searching our database.

Arrays

Thread view: 
slayer_azure - 01 Jun 2007 20:23 GMT
Is it possible to increase the [length] of an array every time a loop
is run without losing data of the previous values. i.e I want to store
an element in an array everytime the loop is run but don't know how
many elements will be stored and therefore have to increase the length
by 1 everytime.
Robert Klemme - 01 Jun 2007 20:46 GMT
> Is it possible to increase the [length] of an array every time a loop
> is run without losing data of the previous values. i.e I want to store
> an element in an array everytime the loop is run but don't know how
> many elements will be stored and therefore have to increase the length
> by 1 everytime.

Arrays cannot be resized.  Use one of the classes implementing List instead.

    robert
slayer_azure - 02 Jun 2007 22:59 GMT
How do you use List. Can anyone give an example.

Sorry, I know it's a easy question but I'm a Grade 11 I.T student and
still a newbie.
Robert Klemme - 03 Jun 2007 09:46 GMT
> How do you use List. Can anyone give an example.
>
> Sorry, I know it's a easy question but I'm a Grade 11 I.T student and
> still a newbie.

Obviously you have internet access.  There is a good tutorial about Java
on Sun's site.  And then there is Google...

    robert
slayer_azure - 03 Jun 2007 15:42 GMT
> > How do you use List. Can anyone give an example.
>
[quoted text clipped - 5 lines]
>
>         robert

Thanks. I just got the tutorial. It's quite easy to follow actually.
Hal Rosser - 01 Jun 2007 22:56 GMT
> Is it possible to increase the [length] of an array every time a loop
> is run without losing data of the previous values. i.e I want to store
> an element in an array everytime the loop is run but don't know how
> many elements will be stored and therefore have to increase the length
> by 1 everytime.

VB has the dynamic array where you can "redim" it to another size or "redim
preserve" to resize it without nuking the contents - but Java has the
ArrayList<yourType> and related lists which is easier to work with anyway.
HTH
IchBin - 02 Jun 2007 04:43 GMT
> Is it possible to increase the [length] of an array every time a loop
> is run without losing data of the previous values. i.e I want to store
> an element in an array everytime the loop is run but don't know how
> many elements will be stored and therefore have to increase the length
> by 1 everytime.

You could use a list but if you insist to use an array I have an
example. I wrote a JTable Model to handle sorting. I have some methods
that needs to dynamical expand and keep its data. So the following code
is what I wrote:

=====> This is what I do for adding a column.

protected void addColumn(String columnName)
{
    if (columnNames == null)
    {
        //
        // First time
        this.columnNames = new String[1];
        this.columnNames[0] = columnName;
    } else
    {
        // Create temp Object to hold current columns data plus one new
        // empty element
        Object temp[] = new Object[columnNames.length + 1];
        //
        // Copy all current Column data to temp
        System.arraycopy(columnNames, 0, temp, 0, columnNames.length);
        //
        // Added the new column name to the temp Object
        temp[temp.length - 1] = columnName;
        //
        // Rebuild the Instance Column object with all of the new data
        this.columnNames = new String[temp.length];
        System.arraycopy(temp, 0, columnNames, 0, columnNames.length);
    }
}

=====> This is what I do for adding a row.

protected void addRow(Object[] data)
{
    if (this.data == null)
    {
        this.data = new Object[1][data.length];
        //
        // loop and add the new first data row elements
        for (int j = 0; j < data.length; j++)
        {
            this.data[0][j] = data[j];
        }
    } else
    {
        //
        // Create temp Object to hold current columns data plus one new
        // empty element
        Object temp[][] = new Object[this.data.length + 1][data.length];
        //
        // Copy all current Column data to temp
        copyObjects(this.data, temp);
        //
        // Add the new column data elements
        for (int outer = 0; outer < data.length; outer++)
        {
            temp[temp.length - 1][outer] = data[outer];
        }
        //
        // Rebuild the Instance data object with all of the new data
        this.data = new Object[temp.length][data.length];
        copyObjects(temp, this.data);
        //
        // Display the data if in debug mode
        if (DEBUG) printDebugData(this.data);
        //
        // Update the JTable display with new data
        fireTableDataChanged();
    }
}

/**
 * I added this Method as a helper to manage the data[][] expansion
 *
 * @param fromdata    the data[]][] object to copy from
 * @param todata      the data[]][] object build target
 *
 * @return Object[][] return the build data[][] object
 */
protected Object[][] copyObjects(Object[][] fromdata, Object[][] todata)
{
    for (int outer = 0; outer < fromdata.length; outer++)
    {
        for (int inner = 0; inner < fromdata[outer].length; inner++)
        {
            todata[outer][inner] = fromdata[outer][inner];
        }
    }
    return todata;
}

private void printDebugData(Object[][] data)
{
    int numRows = data.length;
    int numCols = data[0].length;

    out.println();

    for (int i = 0; i < numRows; i++)
    {
        out.print("    row " + i + ":");
        for (int j = 0; j < numCols; j++)
        {
            out.print("  " + data[i][j]);
        }
        out.println();
    }
}

Signature

Thanks in Advance...           http://weconsulting.org
IchBin, Philadelphia, Pa, USA http://ichbinquotations.weconsulting.org
______________________________________________________________________
'If there is one, Knowledge is the "Fountain of Youth"'
-William E. Taylor, Regular Guy (1952-)

The Billboard Hot 100 - 02 Jun 2007 10:36 GMT
You could also create your own set.
You may also extend it by using AbstactSet to make it iterable.
Cheers...

package deneme;

import java.util.*;

/**
*    Items are not in any order
*/

public class MyArray <E> {

 private static int FIRSTCAPACITYOFARRAY = 20;
 private int counter=0;
 private E[] localData;
 private int currentSize;

/**
* Constructs it with capacity of 20 items
*
*/
public MyArray(){
   localData = (E[]) new Object[FIRSTCAPACITYOFARRAY];
 }

/**
* Other constructor to make  a copy of a collection
* @param collection
*/
 public MyArray(Collection <E> collection){
   int size = collection.size();
   size += size/10;
   localData = (E[]) new Object[size];
   for (E item : collection){
     if (item!=null && !contains(item))
       localData[counter++]=item;
   }
 }

 /**
  * returns true if the item is added successfully
  */
  public boolean add(E item){
    if(item == null){
        throw new NullPointerException();}
    else if( contains(item)){
        return false;}
    else{
        ensureTheCapacity ();
        localData[counter++] = item ;
        return true ;
        }
     }

/**
 * returns the size
 */
 public int size () {
   return localData.length +1 ;
 }
 /**
  * Returns index of the given item if it is not in the array returns
-1
  * @param item
  * @return index
  */
   private int findIndex(Object item){
    if(item == null){
         throw new NullPointerException();}

     for (int i = 0 ; i< counter ; i++){
            if (item == localData[i]){
             return i;}
         }
     return -1;
   }

 /**
  *
  * @param index
  * @return E
  */
 public E get(int index) {
     if(index<0||index>=counter)
       throw new IndexOutOfBoundsException();
     return localData[index];
   }

/**
* returns true if the array is empty otherwise false
*/
 public boolean isEmpty(){
      return localData[0] == null;
 }

/**
* Returns true if the item is in the array
*/
 public boolean contains(Object item){

  for (int i = 0 ; i< counter ; i++){
       if (item == localData[i])
           return true;
       }
   return false;
 }

/**
*  Removes the given item if it match
*/
 public boolean remove (Object localItem) {

   for (int i = 0 ; i< counter ; i++){
          if (localItem == localData[i]){
          localData[i] = localData[currentSize-1];
          localData[currentSize-1] = null;
          return true;}
       }
   return false;
 }

/**
* Make sure that there is sufficient place in the array
*
*/
 private void ensureTheCapacity () {
   if(counter<localData.length){ return; }

   E[] temporaryArray = (E[]) (new Object[localData.length
+FIRSTCAPACITYOFARRAY]);
   for(int i =0 ; i<counter ; i++)
   {
       temporaryArray[i] = localData[i];
       localData = temporaryArray;
   }
 }

}
Arne Vajhøj - 02 Jun 2007 18:02 GMT
> Is it possible to increase the [length] of an array every time a loop
> is run without losing data of the previous values. i.e I want to store
> an element in an array everytime the loop is run but don't know how
> many elements will be stored and therefore have to increase the length
> by 1 everytime.

As other have already told you then various collections especially
ArrayList seems perfect for your usage.

If you insist on using an array and you just happen to be on
Java 1.6 (or 6 for those who prefer that name) then look at
the Arrays.copyOf methods.

Arne
slayer_azure - 02 Jun 2007 23:01 GMT
I've Googled Array.copyOf and can't find an easy example. Have you
used it before and can you paste your program?
Arne Vajhøj - 03 Jun 2007 00:07 GMT
> I've Googled Array.copyOf and can't find an easy example. Have you
> used it before and can you paste your program?

import java.util.*;

public class AR16 {
    public static void main(String[] args) {
        int[] ia = new int[2];
        ia[0] = 1;
        ia[1] = 2;
        int[] ia2 = Arrays.copyOf(ia, 4);
        ia2[2] = 3;
        ia2[3] = 4;
        for(int i = 0; i < ia2.length; i++) {
            System.out.println(ia2[i]);
        }
    }
}

Arne
Arne Vajhøj - 03 Jun 2007 00:08 GMT
>> I've Googled Array.copyOf and can't find an easy example. Have you
>> used it before and can you paste your program?
[quoted text clipped - 14 lines]
>     }
> }

And ia could have been used instead of ia2.

Arne
slayer_azure - 03 Jun 2007 15:43 GMT
On Jun 3, 1:07 am, Arne Vajh?j <a...@vajhoej.dk> wrote:
> > I've Googled Array.copyOf and can't find an easy example. Have you
> > used it before and can you paste your program?
[quoted text clipped - 17 lines]
>
> Arne

Thanks a lot. It's just what I needed.
Joshua Cranmer - 03 Jun 2007 19:17 GMT
> If you insist on using an array and you just happen to be on
> Java 1.6 (or 6 for those who prefer that name) then look at
> the Arrays.copyOf methods.
>
> Arne

And if you're using <1.6, you can use System.arraycopy, e.g.:

int[] x = new int {1,2,3,4};
int[] y = new int[x.length+1];
System.arraycopy(x,0,y,0,x.length);
x = y; // Now x is {1,2,3,4,0}


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.