-1
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
    Please read: [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – Turing85 Sep 11 '22 at 15:34
  • 1
    As an aside: Java does not have a notion of "multidimensional arrays" per-se. A two-dimensional array, for example, is only an array of arrays. The "outer array" holds reference to the "inner arrays". – Turing85 Sep 11 '22 at 15:36
  • You're printing `tmp1` twice. – Alexander Ivanchenko Sep 11 '22 at 15:36
  • As @Turing85 said, in fact there's no "multidimensional arrays" in Java. You can create an array containing other array, which in turn can contain other arrays. That's called *nested array*. – Alexander Ivanchenko Sep 11 '22 at 15:40

1 Answers1

0

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.

obourgain
  • 8,856
  • 6
  • 42
  • 57