Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Re-Initialize array without loosing contents..

  1. #1
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re-Initialize array without loosing contents..

    Hello everyone!!!
    Suppose, i've declared a string array. At runtime, i get user's choice and initialize the array size with user given choice.

    Now, suppose
    String array[];

    During run-time user entered 5 and my array size is now 5. Now if a specific condition occur, i want to resize my array. Forexample, a condition occured, and i needed to add 5 more indexes in the array. Means, my array should be of size 10 now without any data loss. I know how to handle the data without loosing it but don't know how to re-initialize my same array to get size 10. I only want to use array and nothing else (i.e. arraylist or vector).

    And is this the right solution (Described below);
    i'll make a function which will initialize my array with user given size. As soon as user enters, array is declared and soon after as i need to extend my array size, i'll call the function. Before that, i'll store whole data in temporary array.

    So, if there are other solutions (efficient one), kindly let me know.

    Waiting....

    Regards...


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Re-Initialize array without loosing contents..

    Use the same method that ArrayList uses (it's commonly used for a lot of good reasons):

    Keep using your array until it gets full.
    When it's full, create a temporary array with double the size as the original one.
    Copy over all of the elements in the initial array into the temporary array.
    Set the original array reference to the temporary one.

    int my_array[] = new int[5];
    //... some how fill up to 5 int's
    int temp_array[] = new int[my_array.length * 2];
    for(int i = 0; i < my_array.length; ++i)
    {
        temp_array[i] = my_array[i];
    }
    my_array = temp_array;

    Note that you'll need an extra int variable to keep track of how many items are actually being used in the array.

  3. #3
    Member
    Join Date
    Jun 2011
    Location
    Rhode Island
    Posts
    69
    My Mood
    Bored
    Thanks
    11
    Thanked 7 Times in 6 Posts

    Default Re: Re-Initialize array without loosing contents..

    Quote Originally Posted by Mr.777 View Post
    i needed to add 5 more indexes in the array. ... how to re-initialize my same array to get size 10.

    And is this the right solution (Described below);
    i'll make a function which will initialize my array with user given size. As soon as user enters, array is declared and soon after as i need to extend my array size, i'll call the function. Before that, i'll store whole data in temporary array.
    well depends on if you know how many elements they are going to enter.
    run this code and you can decide what you want to create.

        public static void main(String[] args) {
            System.out.println("staring a Array[] with 5 elements");
            String[] myString ={"Bob","Tim","Robert","Julie","Mark"};
            System.out.println("my array has this many elements: " + myString.length);
            System.out.println("assign a new array with 10 elements");
     
            /*created a new String array*/
            String[] newString = new String[myString.length * 2];
     
            /*loop to assign my new elements */
            for (int i = 0; i < myString.length; i++) {
                newString[i]=myString[i];
                System.out.println("string name is " + myString[i]);
            }
     
            System.out.println("this is how many elements my new string has: " + newString.length);
            /*reference assignment*/
            myString = newString;
            System.out.println("myString has this many elements: " + myString.length);
        }
    }

    call a functions similar to this when you know that you have to double your elements in your array[] then you wont have to worry about it.
    call it expandingArray() method.

  4. #4
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Re-Initialize array without loosing contents..

    Thanks to both of you for helping me.
    But, unfortunatley i couldn't get any new thing.
    @helloworld922: What you are saying, will be efficient in other cases, but in my case, it's really not as i just need to save as much memory as i can.
    @william : The same thing i was thinking and wrote above.

    Anyways, thanks alot, both of you.

    May you stay happy always.

    Good luck.

  5. #5
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: Re-Initialize array without loosing contents..

    You can use the Arrays.copyOf(..) methods to copy the contents of an existing array into a longer one. Basically they use System.arraycopy(..) to copy the array contents. In the end, it's just a slightly better way to do what the other code posted here does.

  6. #6
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Re-Initialize array without loosing contents..

    @dlorde: Thanks alot. I'll definitely give it a try and if problem persists, i'll come back here

  7. #7
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Re-Initialize array without loosing contents..

    Quote Originally Posted by Mr.777 View Post
    @helloworld922: What you are saying, will be efficient in other cases, but in my case, it's really not as i just need to save as much memory as i can.
    Expanding the array size by twice the existing size is not a requirement, but rather a suggestion. You can choose to expand the array in any increment you want (for example, always expand by 10 elements, or double the capacity until you get to 1000 elements, then start expanding by 100).

    Using a standard array, that is the only method if you intend to "extend" the array. You will always need two arrays: The current smaller one which holds all the data, and the new larger array which you're copying data into. After the copy, the smaller array can be garbage collected to reclaim that memory.

    Every other method described is some variation of this method (including Array.copyOf(), and even the ArrayList class).

    The only other option is to use a different data structure. Since you said you're storing strings, I would suggest developing either a trie or radix tree (or using one someone else has written). Strings tend to lend themselves very well to being stored in tries and radix trees, and are both extremely fast and memory efficient.
    Last edited by helloworld922; June 17th, 2011 at 01:40 AM.

  8. #8
    Think of me.... Mr.777's Avatar
    Join Date
    Mar 2011
    Location
    Pakistan
    Posts
    1,136
    My Mood
    Grumpy
    Thanks
    20
    Thanked 82 Times in 78 Posts
    Blog Entries
    1

    Default Re: Re-Initialize array without loosing contents..

    @helloworld922: Sure and thanks again. I'll study about radix trees in depth. Thanks for support.

Similar Threads

  1. Trouble apending a textArea with the contents of a parameter
    By bluetxxth in forum What's Wrong With My Code?
    Replies: 1
    Last Post: November 21st, 2010, 04:28 PM
  2. Reading contents of another window
    By jimmys in forum Java Theory & Questions
    Replies: 8
    Last Post: October 4th, 2010, 11:40 PM
  3. How to create a sorted set from the contents of an array
    By davie in forum Collections and Generics
    Replies: 1
    Last Post: March 11th, 2010, 03:44 PM
  4. Convert contents of JTextArea / JEditorPane to PDF
    By rangarajank in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: September 30th, 2009, 02:38 PM
  5. I'm not sure how to initialize GraphicsDevice and Window
    By DotChris in forum AWT / Java Swing
    Replies: 3
    Last Post: July 15th, 2009, 09:00 AM