I have several arrays in a class
I want to implement toString() to print all values.
How to do this?
public String var1[];
public int var2
String someArray = new String[] {"1", "2"};
String toString = Arrays.asList(someArray).toString();
The code above will print out the toString in a more readable format:
[1, 2]
If you are using JDK 1.5, you can use:
String[] strings = { "ABC", "DEF" };
String s = Arrays.toString(strings);
First of all, it depends on the size of your arrays. You did not mention any size for each of it. Of course, we can use for each
. The second question obviously, how to want to print them all in the screen. that is the matter.
In case, if you go with normal for loop
[ex: for(int i=0;i<ar.length();i++)]
in this case. You have to go by individual loop for each array.
If your array size is same for all. You can simply use one loop to iterate all of them to print it off.
Hint: don't forget to handle the ArrayOutofBound exception. You would need that :P
I think what you are looking for is Arrays.deepToString()
Refer to this link for more details. It takes an array and calls toString()
on every element.
You can use the Arrays.toString() static helper method as follows:
String lines[] = getInputArray();
System.out.println(java.util.Arrays.toString(lines));