开发者

toString java of arrays

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[];
public String var3开发者_Go百科[][];
public int var4[];
public int var5[][];

public String toString() {

        for(String s :  var1) {
              System.out.println(s.toString());           
        }


        return  null;
    }

That prints all var1[] content but how to print all?? Do I have to put a loop for every one of them?


You can use the Arrays.toString() static helper method as follows:

String lines[] = getInputArray();
System.out.println(java.util.Arrays.toString(lines));


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.


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


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); 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜