Reputation:
In my previous question I found out how to print each array of a 2d array, now I finished this code below. I'd like to know if this is one / the fastest way of doing it? This should be in linear time because we have only if-statements and not nested for-loops (?)
If it's not, please tell me what would be the most efficient way?
public class Print{
public static void main(String[] args){
int[][] myArray = {{1,2,3,4},{5,6,7,8}};
int i=0;
System.out.print("[");
for(int j=0; j<myArray[0].length; j++){
System.out.print(myArray[i][j]);
if(j != myArray[0].length-1){
System.out.print(", ");
}
if(j == myArray[0].length-1){
System.out.print("], ");
}
}
int k=1;
System.out.print("[");
for(int j=0; j<myArray[1].length; j++){
System.out.print(myArray[k][j]);
if(j != myArray[1].length-1){
System.out.print(", ");
}
if(j == myArray[1].length-1){
System.out.print("]");
}
}
}
}
Output: [1, 2, 3, 4], [5, 6, 7, 8]
Edit: I'm not looking for a way to code this shorter. I'm rather looking for the speed of algorithm, the fastest.
Upvotes: 0
Views: 187
Reputation: 1241
You can easily use the code like this:
int[][] myArray = {{1,2,3,4},{5,6,7,8}};
System.out.print(Arrays.deepToString(myArray));
It will be a lot faster.
Upvotes: 1