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.

1

3 Answers 3

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

Comments

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.

3 Comments

I'm sorry but your link doesn't clarify how I messed up. Initializing the array as String[2] allows positions 0 and 1, no?
Are you saying the argument passed should explicitly also be a String[2]?
@mitbanip You decalred an array with length 2 and later ovveriding it with setter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.