What's the simplest way to print a Java array? -


in java, arrays don't override tostring(), if try print 1 directly, weird output including memory location:

int[] intarray = new int[] {1, 2, 3, 4, 5}; system.out.println(intarray);     // prints '[i@3343c8b3' 

but we'd want more [1, 2, 3, 4, 5]. what's simplest way of doing that? here example inputs , outputs:

// array of primitives: int[] intarray = new int[] {1, 2, 3, 4, 5}; //output: [1, 2, 3, 4, 5]  // array of object references: string[] strarray = new string[] {"john", "mary", "bob"}; //output: [john, mary, bob] 

since java 5 can use arrays.tostring(arr) or arrays.deeptostring(arr) arrays within arrays. note object[] version calls .tostring() on each object in array. output decorated in exact way you're asking.

examples:

simple array:

string[] array = new string[] {"john", "mary", "bob"}; system.out.println(arrays.tostring(array)); 

output:

[john, mary, bob] 

nested array:

string[][] deeparray = new string[][] {{"john", "mary"}, {"alice", "bob"}}; system.out.println(arrays.tostring(deeparray)); //output: [[ljava.lang.string;@106d69c, [ljava.lang.string;@52e922] system.out.println(arrays.deeptostring(deeparray)); 

output:

[[john, mary], [alice, bob]] 

double array:

double[] doublearray = { 7.0, 9.0, 5.0, 1.0, 3.0 }; system.out.println(arrays.tostring(doublearray)); 

output:

[7.0, 9.0, 5.0, 1.0, 3.0 ] 

int array:

int[] intarray = { 7, 9, 5, 1, 3 }; system.out.println(arrays.tostring(intarray)); 

output:

[7, 9, 5, 1, 3 ] 

Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -