user1285707
user1285707

Reputation:

How to add item in array?

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];

        }   

Upvotes: 0

Views: 389

Answers (5)

aioobe
aioobe

Reputation: 420991

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");

Upvotes: 3

ccheneson
ccheneson

Reputation: 49410

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];
}

Upvotes: 0

Vinayak Bevinakatti
Vinayak Bevinakatti

Reputation: 40503

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

Upvotes: 0

Murat Nafiz
Murat Nafiz

Reputation: 1438

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

Upvotes: 0

Denys Séguret
Denys Séguret

Reputation: 382150

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);
}

Upvotes: 0

Related Questions