Simple use of Vector in Java

Source: Internet
Author: User

Similar to vector in C ++, it can also store various types of elements.

Import java. util. vector;


Eg.

Vector ivec = new vector ();

Vector ivec = new vector (10); // ivec with an initial length of 10

Vector ivec = new vector (10, 5); // The initial length is 10. When the space is insufficient, the length increases by 5.


Ivec. Add (5); // Add element 5

Ivec. Add (INT index, object value); // Add the element value at the index position. After insertion, other elements are removed.

Ivec. Set (INT index, object value); // change the element value with index to value.

Object OBJ = ivec. Get (INT index); // obtain the value of the element whose index is index.

Ivec. Remove (INT index); // Delete the element whose index is located.

Ivec. tostring (); // converts all elements into strings for output.


When deleting all elements from a vector in C ++ and C ++, you must note that deleting an element in C ++ will invalidate the iterator, as shown below:

For (STD: vector <int >:: iteator iter = VEC. Begin (); iter! = Vec. End (); ++ ITER)

{

VEC. Erase (ITER); // error! This will not delete all elements correctly.

}

The reason why all elements cannot be deleted correctly is that the iterator fails after Vec. Erase (ITER), which should be written in the following method:

For (STD: vector <int >:: iteator iter = VEC. Begin (); iter! = Vec. End ();)

{

If (condition)

{

Iter = Vec. Erase (ITER); // Save the value of each iterator. After deletion, ITER points to the next element to be deleted.

}

Else

{

++ ITER;

}

}

Similarly, when deleting all elements in Java:

For (INT I = 0; I <ivec. Size ();)

{

Ivec. Remove (I); // or ivec. Remove (0 );

}



System. Out. println ("output all elements in string form:" + ivec. tostring ());



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.