user319940
user319940

Reputation: 3317

Multiple Array toString in Java

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.

Upvotes: 1

Views: 2760

Answers (2)

notk0
notk0

Reputation: 11

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.

Upvotes: 0

aioobe
aioobe

Reputation: 420951

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

Upvotes: 6

Related Questions