tags:

views:

132

answers:

5

How do you:
1. Initialize (create) an Array.
2. Push a String value into it.
3. Push another String value into it.
4. Dump it to get its contents.

+6  A: 

Arrays in Java are a fixed size, determined when you create them. As such, they have no push methods.

It sounds like you want a List instead, most likely an ArrayList<String>. Lists have an add function for adding new elements.

The Java Collections trail has more information about the various types of collections (List, Set, and Map).

Lists and Sets work with Java's for each operator:

List<String> myList = new ArrayList<String>();
//List<String> myList = new LinkedList<String>();

myList.add("One");
myList.add("Two");

// Because we're using a Generic collection, the compiler
// inserts a cast on the next line for you
for (String current : myList) {
    // This section happens once for each elements in myList
    System.out.println(current);
}
// should print "One" and "Two" (without quotes) on separate lines
R. Bemrose
I finally got around to adding an example. Hopefully that helps.
R. Bemrose
Brilliant! Thanks for answering the question I should have asked!
Emanuil
+1  A: 
 anArray = new string[10];
 anArray[0] = "MYSTRING";
 string MyString = anArray[0];

for (int i =0; i <10; i++)
{
   System.out.println(anArray[i]);  
}

Pretty straightforward as far as arrays go, there are a couple of other libraries in java that can help ease the burdens of using raw arrays.

Gnostus
+2  A: 
int[] a;
a = new int[5];

a[0]=1;
a[1]=2;
a[2]=3;
a[3]=4;
a[4]=5;

for(int i =0; i<5; i++)
   System.out.println(a[i]);

Java.sun has a good link for array help: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html This is basically a fixed size array. If you are looking to push elements in (you do not know the size) you'll want to look at an ArrayList.

JonH
+1  A: 

Why not use a Stack?

final Stack<String> strings = new Stack<String>();
strings.push("First");
strings.push("Second");
System.out.println(strings.toString());

You could also use a List or a Queue depending on your needs.

Ben S
I wasn't aware that toString on a collection would work, but I guess it makes sense.
R. Bemrose
Yeah, it prints a nice little list calling `.toString()` on each element in turn. :D
Ben S
+1  A: 

It does sound like you want a list, but in case you really did mean an array...

//1. 
String [] arr = new String[2];
//2.
arr[0] = "first";
//3.
arr[1] = "second";
//4.
for (String s: arr)
{
    System.out.println(s);
}
BioBuckyBall