Java 7中,153个 141 114字节
String r="";<T,S>S c(S s,T o){for(T x:(T[])o)if(x instanceof Object[])c("-"+s,x);else r+=s+">"+x+"\n";return(S)r;}
-39字节感谢@ Barteks2x
说明:
String r=""; // Result String outside the method / on class-level
<T,S> S c(S s, T o){ // Recursive Method with generic String and Object parameters and String return-type
for(T x : (T[])o) // Loop over the input-array
if(x instanceof Object[]) // If the current item is an array itself:
c("-"+s, x); // Recursive method-call with this array
else // Else:
r += s+">"+x+"\n"; // Append return-String with stripes String-input, ">", current item, and a new-line
// End of loop (implicit / single-line body)
return (S)r; // Return the result-String
} // End of method
测试代码:
在这里尝试。
class M{
String r="";<T,S>S c(S s,T o){for(T x:(T[])o)if(x instanceof Object[])c("-"+s,x);else r+=s+">"+x+"\n";return(S)r;}
public static void main(String[] a){
M m = new M();
System.out.println(m.c("", new Object[]{new Object[]{1,2},new Object[]{new Object[]{1,2},3},4,new Object[]{new Object[]{new Object[]{new Object[]{5}}}},6}));
m.r = "";
System.out.println(m.c("", new Object[]{"Atom",new Object[]{"Proton",new Object[]{"Up Quark","Up Quark","Down Quark"}},new Object[]{"Neutron",new Object[]{"Up Quark","Up Quark","Down Quark"}},"Electron"}));
}
}
输出:
->1
->2
-->1
-->2
->3
>4
---->5
>6
>Atom
->Proton
-->Up Quark
-->Up Quark
-->Down Quark
->Neutron
-->Up Quark
-->Up Quark
-->Down Quark
>Electron