0

I want add item at the top of array?

how can i achieve this?

there are two item in array. i want to add item at top of the array.

result1 = new String[result.length+1];

            for(int i=result.length;i==0;i--)
        {
            if(i==0)
            {
               result1[0]="Latest";

            }
            result1[i]=result[i-1];

        }   
1
  • Add (or) replace, if add, consider using arraylist and at the end covert it to array? Commented May 11, 2012 at 14:27

5 Answers 5

3

To answer your question: You need to

  1. Create a new array with with size = old length + 1.
  2. Copy the content of the old array to the new array,
  3. Insert "latest" into the new array:

Like this:

String[] result = { "a", "b", "c" };
String[] tmp = new String[result.length+1];

System.arraycopy(result, 0, tmp, 1, result.length);
tmp[0] = "latest";
result = tmp;

But, I encourage you to consider using a List such as ArrayList in which case you could express this as

result.add(0, "latest");
Sign up to request clarification or add additional context in comments.

1 Comment

This is nice, but isn't arraylist will be faster and easy if allowed to use?
0

You can't : an array has a fixed length.

If you want to have variable size "arrays", use ArrayList.

Exemple :

ArrayList<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.set(0, "new a");
for (String s: list) {
    System.out(s);
}

2 Comments

can you give example of arraylist.
result1 = new String[result.length+1]; for(int i=(result.length);i>=0;i--) { if(i==0) { result1[0]="Latest"; } else { result1[i]=result[i-1]; } resultfinal=result1; } */
0

But you can use ArrayList and with add(int index, E object) function you can add items wherever you want. And you can convert ArrayList to array[] easly

Comments

0

Use stack which works as LIFO (Last In First Out), hence whenever you pop (read) you will get the latest(at the top) pushed item

Here is the Java code reference using Array: http://wiki.answers.com/Q/Implementing_stack_operation_using_array_representation_with_java_program

1 Comment

how to add values in arraylist?
0

One problem with your solution is that when i == 0, you set the value to Latest but the value is overwritten after with result1[i]=result[i-1];

Try

if(i==0) {
     result1[0]="Latest";
}
else {
     result1[i]=result[i-1];
}

1 Comment

Only the first item (index 0) will have "Latest"