toString java of arrays

前端 未结 4 790
旧巷少年郎
旧巷少年郎 2020-12-03 15:20

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         


        
相关标签:
4条回答
  • 2020-12-03 15:36
    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 讨论(0)
  • 2020-12-03 15:41

    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

    0 讨论(0)
  • 2020-12-03 15:52

    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.

    0 讨论(0)
  • 2020-12-03 15:56

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

    String lines[] = getInputArray();
    System.out.println(java.util.Arrays.toString(lines));
    
    0 讨论(0)
提交回复
热议问题