简体   繁体   中英

How we can increase size of 2d vector in Java?

Assume we defined a 2d vector in Java. Size of the first dimension is 10 and size of second dimension is 1 . Now if we want to increase size of first dimension of this 2d vector what should we do?

Assume we want add number 1 to 30th cell (ie v1[29][0]=1 ), but our vector size is 10 .

Here is my code in Java:

Vector [][] v1 = new Vector [10][];

for (int i=0 ; i<10; i++)
    if (i==0) {
        v1[i]=new Vector[1];
    }
    else
        v1[i]=v1[0];
v1[0][0]=new Vector(1);

You need to assign new, bigger array, for example v1 = new Vector[30][] .

Note that Vector is synchronized. If a thread-safe implementation is not needed, it is recommended to use ArrayList in place of Vector .

Also, make sure that you understand what are you doing. If you only need to "add number 1 to 30th cell (ie v1[30][0]=1)", then int v1 = new int[31][] should be enough, without any vectors. By the way, 30th cell is v1[29][0] , not v1[30][0] , watch out for this common mistake-by-one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM