-1

Do I keep many arrays in a vector? I want like this... [{1,2,3},{4,5,6},{7,8,9},{10,11,12}]

I am trying in this way and get error.

          Vector< int[]> v=new Vector();
            for(int i=0;i<n;i++){
                int a[]=new int[3];
                for(int j=0;j<3;j++){
                    a[j]=ob.nextInt();
                }
                v.add(a);
            }
            for(int i=0;i<n;i++){
                System.out.println(v.get(i));
            }

I know this way

         Vector< Vector<Integer>> v=new Vector();
            for(int i=0;i<n;i++){
            Vector< Integer> v1=new Vector();
                for(int j=0;j<3;j++){
                    v1.add(ob.nextInt());
                }
                v.add(v1);
            }
            for(int i=0;i<n;i++){
                System.out.println(v.get(i));
            } 

But I want to keep those element (in a vector) using array .Can I?

Shoukhin78
  • 53
  • 8

2 Answers2

1

If you really want use Vector, you can try something like this (I assume, your ob is Random object):

Random ob = new Random();
final int n = 3;

Vector<int[]> v = new Vector<>();

for (int i = 0; i < n; i++) {
    int[] a = new int[n];
    for (int j = 0; j < n; j++) {
        a[j] = ob.nextInt();
    }
    v.add(a);
}

for (int i = 0; i < v.size(); i++) { //changed
    for (int j = 0; j < v.get(i).length; j++) {
        System.out.println(v.get(i)[j]);
    }
}

you were probably surprised by the display of int [] on your console. In my case:

[I@7229724f
[I@4c873330
[I@119d7047

You can read more about it here.

But I recommend change Vector to List (you can read this for more details).

M. Dudek
  • 978
  • 7
  • 28
0

You can also use NOT primitive type with

Vector<Integer[]> v = new Vector();

But, what's the problem? Where is the error?

 Scanner ob = new Scanner(System.in).useDelimiter("\\s");
 int n = 2;
 Vector<int[]> v = new Vector();
 for (int i = 0; i < n; i++) {
     int[] a = new int[3];
     for (int j = 0; j < 3; j++) {
         a[j] = ob.nextInt();
     }
     v.add(a);
 }
 for (int i = 0; i < n; i++) {
     System.out.println(Arrays.toString(v.get(i))); //change output
 }

Input: 1 2 3 4 5 6

Output: [1, 2, 3] [4, 5, 6]

devalurum
  • 58
  • 7