Results 1 to 3 of 3
  1. #1
    VeasMKII's Avatar
    VeasMKII is offline Member
    Join Date
    Jan 2009
    Posts
    18
    Rep Power
    0

    Default [SOLVED] Shifting an array

    I have an array that contains 20 values:
    Java Code:
    int[] data = {0,1,2...20} //pesudo-code
    I want to be able to add new values, each time removing the first and shifting them all down one

    so for example

    data[x] = 56; //21st value

    so the new array will read {1,2,3..20,21} //first entry has been removed and everything moved down like in a list

    Basically the same idea as the following:

    Java Code:
    if ( list.size > 19){
         list.removeElementAt(0);
         list.addElement(i);
    }
    *edit*
    Actually, my mind escaped me for a moment, i've got an idea for it

    Java Code:
            for (int i =0; i < data.length;i++){
                if(i < 19){
                    data[i] = data[i+1];
                } else if (i == 19){
                    data[19] = intval;
                }
            }
    Last edited by VeasMKII; 01-31-2009 at 03:33 PM.

  2. #2
    Jasonre is offline Member
    Join Date
    Jan 2009
    Posts
    40
    Rep Power
    0

    Default

    use an ArrayList instead, makes it a lot easier to add to the list.

  3. #3
    emceenugget is offline Senior Member
    Join Date
    Sep 2008
    Posts
    564
    Rep Power
    7

    Default

    1. you do realize that your array has 21 items and not 20?
    2. it's a lot better practice to use properties of the array (or whatever container you decide to use) to iterate through it as opposed to hard-coding the value (in your case 19).
    3. as Jasonre, an ArrayList would make this simpler, though you would need to use the Integer wrapper class.

Similar Threads

  1. Sum of Array
    By Mika in forum New To Java
    Replies: 4
    Last Post: 01-03-2009, 10:38 AM
  2. Array Reflection: Multi Array Reflection
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-23-2008, 09:08 PM
  3. can anyone help... 2d Array
    By Mark1989 in forum New To Java
    Replies: 2
    Last Post: 03-12-2008, 09:59 PM
  4. 2D array
    By bluekswing in forum New To Java
    Replies: 2
    Last Post: 01-15-2008, 06:57 PM
  5. Help with Array
    By susan in forum New To Java
    Replies: 1
    Last Post: 08-07-2007, 05:32 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •