tags:

views:

129

answers:

5

Hey,

I have not been able to find a proper answer on any forums about this.
But how exactly do I pass an array to a class constructor?

public class TestArray {
   String name;
   String[] array;

   public TestArray(String name, String[] anArray){
          this.name = name;
          int len = anArray.length;
          this.array = new String[len];
          for (int i = 0; i < len; i++)
          {
              this.array[i] = new String(anArray[i]);
          }
   }

   public static void main(String[] args){
        String[] anArray = new String[2];
        anArray[0] = new String("Test");
        anArray[1] = new String("Test2");
        TestArray work = new TestArray("Jordan", anArray); // How to pass the array?
   }
}
+2  A: 

Your code will work, minus the question mark in the last line (edit - this was removed by the editor).

Your braces are also off - move the main function inside the class (you have one too many closing braces after the TestArray constructor).

Edit 2 - now that your question has been edited to fix your errors, it should work as expected. I am not sure if this is the best practice for SO, but that's a discussion for meta.

danben
Wow this was exactly the problem. I had one to many braces and changing that one bracket made everything work. THANks!
ambidextorous
A: 

Exactly like you wrote...

Update:

Maybe you got a compiling error, if so, you placed a closing braces (}) too much in your code. I removed it by formatting your code. Maybe this was the problem...

Martijn Courteaux
A: 

Arrays are objects - so are passed them by reference. And you don't need to make copies yourself. If you really feel you have to copy then better use System.arraycopy.

Anton
'so are passed them by reference'. close, but not true: http://stackoverflow.com/questions/40480/is-java-pass-by-reference
seanizer
your reasoning is otherwise correct, but technically a reference is passed by value
seanizer
@seanizer: agree - java passes references by value :)
Anton
A: 
ShinTakezou
+1  A: 
public static void main(String[] args){
    String[] anArray = new String[2];
    anArray[0] = new String("Test");
    anArray[1] = new String("Test2");
    TestArray work = new TestArray("Jordan", anArray);
}

This will work perfectly, although there is a shorter way to initialize anArray:

public static void main(String[] args){
    String[] anArray = new String[] { "Test", "Test2" };
    TestArray work = new TestArray("Jordan", anArray);
}

Which in turn can be shortened to:

public static void main(String[] args){
    TestArray work = new TestArray("Jordan", new String[] { "Test", "Test2" });
}

By the way, String objects are immutable, so you don't have to initialize new strings every time. They can be used directly like this.

Last tip: Arrays.copyOf(anArray, anArray.length) also returns a copy of the array, without the the for-loop.

Marc
Thanks for the tip for copying the array.
ambidextorous