1

I'm trying to override the toString method in Java to output from two arrays (of strings) into a string which I can then format with line breaks, which I assume use /n. I'm just getting to grips with Java and after looking at the documentation I'm still baffled as to how the syntax for something like this should look. If someone has an example they could show me or can explain a good method of doing this I would be most grateful.

1
  • When you say you want to process 2 arrays on strings into a single string. You mean that you want arrays {"This", "is", "a"} {"random", "sentence"} to become a string like "This/nis/na/nrandom/string"? If not would you clarify what exactly you want? Commented Feb 7, 2011 at 21:23

2 Answers 2

6

If you have a class with two arrays, and want to override the toString method to show these you do:

@Override
public String toString() {
    return Arrays.toString(array1) + " " + Arrays.toString(array2);
}

Here is a complete example:

import java.util.Arrays;

public class Test {

    int[] array1 = { 1, 2, 3 };
    String[] array2 = { "Hello", "World" };

    @Override
    public String toString() {
        return Arrays.toString(array1) + " " + Arrays.toString(array2);
    }

    public static void main(String[] args) {
        System.out.println(new Test());
    }
}

Output:

[1, 2, 3] [Hello, World]

Here is a version with new-lines:

public class Test {

    int[] array1 = { 1, 2, 3 };
    String[] array2 = { "Hello", "World" };

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("array1:\n");
        for (int i : array1)
            sb.append("    ").append(i).append('\n');

        sb.append("\narray2:\n");
        for (String s : array2)
            sb.append("    ").append(s).append('\n');

        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(new Test());
    }
}

Output:

array1:
    1
    2
    3

array2:
    Hello
    World
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this looks to be exactly the sort of example I was looking for. I'll let you know how it goes :D thanks again.
If this seems to work for what you asked, it'd be nice to mark the answer as correct.
0

To overwrite toString you need to create a new Class since it's inherited from Object, and it doesn't take two arguments, if you make an Class that has 2 Array Strings inside it then you could definitely do this.

Comments

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.