A one-dimensional array and a two-dimensional array with the same behavior

Viewed 34
package hosein.testFile;

import java.util.*;
import java.io.*;

/**
*
* @author hosein
*/
public class Main2 implements Serializable {

   /**
    * @param args the command line arguments
    */
   public static void main(String[] args) {
       // part 1 ----------------------------------------------------
       ArrayList s = new ArrayList<>();
       ArrayList<String> d = new ArrayList<>();
       ArrayList<String> b = new ArrayList<>();
       d.add("a");
       d.add("b");

       b.add("c");
       b.add("d");
       b.add("e");

       Collections.addAll(s, d, b);
       Object[] tmp1 = s.toArray();
       System.out.println("tmp1 :" + Arrays.toString(tmp1));
       // part 2 ----------------------------------------------------
       Object[][] tmp2 = new Object[2][];
       tmp2[0] = new Object[2];
       tmp2[1] = new Object[3];
       Object[] dTmp = d.toArray();
       Object[] bTmp = b.toArray();
       for (int i = 0; i < tmp2.length; i++) {
           for (int j = 0; j < tmp2[i].length; j++) {
               if (i == 0) {
                   tmp2[i][j] = dTmp[j];
               }
               if (i == 1) {
                   tmp2[i][j] = bTmp[j];
               }
           }
       }
       System.out.println("tmp2 :" + Arrays.toString(tmp1));

   }

}

tmp1 is defined as a one-dimensional array and tmp2 is defined as a two-dimensional array But this behavior is two nights together. What is the reason?

And the output of this code:

run:
tmp1 :[[a, b], [c, d, e]]
tmp2 :[[a, b], [c, d, e]]
BUILD SUCCESSFUL (total time: 0 seconds)
1 Answers

Your example should output:

tmp1 :[[a, b], [c, d, e]]
tmp2 :[[Ljava.lang.Object;@5442a311, [Ljava.lang.Object;@548e7350]

The Array.toString does the loop over the (first dimension of the) array, and call toString() for each element. It is equivalent to :

System.out.print("[" + dimX[0].toString() + "," + dimX[1].toString() + (...) + "]");

For dim1, each element is a java.util.ArrayList, for which toString returns something like [a,b].

For dim2, each element is a 1 dimension array, for which toString returns something like [Ljava.lang.Object;@5442a311.

Related