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.
-
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?Varun Madiath– Varun Madiath2011-02-07 21:23:56 +00:00Commented Feb 7, 2011 at 21:23
Add a comment
|
2 Answers
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
2 Comments
user319940
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.
Varun Madiath
If this seems to work for what you asked, it'd be nice to mark the answer as correct.