Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am using .toString to return a string representation of an object, i.e.

jcb.engineMove(move.toString());

will produce e2e4.

What I am trying to do is to extract the text of this object (e2e4) as a string. After Googling I came across overriding the toString method so I came up with this:

@Override
public String toString() {
    String s = "";
    int newRank = getRank();
    int newFile = getFile();
    final Move move = new Move(rank, file, newRank, newFile);
    s+="" + move;
    return s;
}

My questions are fairly basic:

  1. is this the right approach
  2. How do I call this routine when trying to get the text of the object?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
308 views
Welcome To Ask or Share your Answers For Others

1 Answer

Overriding Object.toString is a good approach.

However, your current implementation makes a major mistake by creating a new Move object (see below).

To call the routine (once you fix it), do exactly what you're already doing:

jcb.engineMove(move.toString());

If toString() should only be used for debugging (as mre says) you could implement another method named getText that does the same thing.

IMPORTANT NOTE:

You should not be creating a new Move object inside its toString method.

This is a very bad idea (as mentioned by others).

Your toString method should simply build a string and return it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...