0

I have a tree with nodes which are named by their coordinates. I just bunched these two separate coordinates up into a single String[] coordinates like so

 class Node {
      private String[] coordinates;

      public Node(){
          coordinates = new String[2];
      }

 public setCoordinates(String[] coordinates){
     this.coordinates = coordinates;
 }

I'm sure the solution must be simple. Assume I don't want a special setter which takes two strings and sets them individually, coordinates[0] = X, coordinates[1] = Y. That's pretty obvious. How could I pass an array of Strings to the fixed-length setter?

I tried

 setCoordinates({"-44.55", "55.22"});

and

  setCoordinates(["-44.55", "55.22"});

also tried passing new String[2] = {} and with [], but those don't work either.

mitbanip
  • 179
  • 3
  • 13
  • Possible duplicate of [Any way to declare an array in-line?](http://stackoverflow.com/questions/1154008/any-way-to-declare-an-array-in-line) – Bö macht Blau Oct 05 '15 at 17:04

3 Answers3

3

You'd have to write setCoordinates(new String[] {"-44.55", "55.22"}). (That's bad enough that you should really be doing this the normal way with two arguments.)

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
  • That was fast :) Assigning String[] was messing me up. Thanks to you both. Will mark as answer when it allows me. edit: And I am passing arguments. I just wanted to make it clearer this way. – mitbanip Oct 05 '15 at 16:50
2
setCoordinates({"-44.55", "55.22"});

instead use below

setCoordinates(new String[]{"-44.55", "55.22"});

Create the String array and pass the arguments in curly brackets.

YoungHobbit
  • 13,254
  • 9
  • 50
  • 73
0

You should try

setCoordinates(new String[]{"-44.55", "55.22"});

That resolves your syntax problem.

Reason : difference between these 2 ways of initializing an simple array

And if I see carefully, you have messedup with your length and initialization part.

You created an array with length of 2. But later you are overriding that with set method.

Removing all the mess ,you need not worry about your constructor part. Just remove it and use only setter if you don't have a restriction of 2 elements.

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307