V: the vector category of Java

Source: Internet
Author: User

It is said that the final exam to test the vector class, for review needs to be here to properly tidy up this class.

First, the basic concept

Vectors are an array of objects that can achieve their own active growth.

Java.util.vector provides a vector class (vector) to implement a function similar to a dynamic array.

There is no concept of pointers in the Java language, but assuming the correct and flexible use of pointers can really improve the quality of the program. For example, in c,c++, the so-called "dynamic array" is usually implemented by pointers. To compensate for this shortcoming. Java provides a rich library of classes to make it easy for programmers to use, and the vector class is one of them.

In fact, the flexible use of arrays can also complete the function of the vector class. But the Vector class offers a large number of methods that are generous enough for the user to use.

After creating an object of a vector class. The ability to arbitrarily insert objects of different classes into them, that is, no need to take into account the type and the capacity of the pre-selected vector. And it is easy to find.

It is not necessary to pre-define the size of the array beforehand, and to search frequently. Insert, delete work condition. Be able to consider using vector classes.

Vectors are vector queues. It is a class added to the JDK1.0 version number. Inherit from Abstractlist. Implements the List,randomaccess, cloneable these interfaces.

The Vector inherits the Abstractlist and implements the list. Therefore, it is a queue, support related to join, delete, change, traverse and other functions.

Vector implements the Randmoaccess interface. The random access function is provided. Randmoaccess is used in Java to be implemented by the list, providing high-speed access to the list. In vector, we are able to get the element object at high speed by the ordinal of the element, which is the high speed random access question.

Vector implements the Cloneable interface. That is, implement the Clone () function. It can be cloned.

Unlike ArrayList, the operations in a vector are thread-safe.

Second, the composition of the vector class

Vector common with 4 constructors

Default constructor

1. Vector ()

Capacity is the default capacity size of the vector. When capacity is added due to the addition of data, it is added one time per capacity.

2, Vector (int capacity)

Capacity is the default capacity size of the vector. The capacityincrement is the increment value each time the vector capacity is added.

3, Vector (int capacity, int capacityincrement)

Create a vector that includes collection

4, Vector (collection< extends e> Collection)

Three member variables

Vector data structures and ArrayList are almost identical. It includes 3 member variables: elementdata, Elementcount. Capacityincrement.

(1) Elementdata is an array of type "object[". It preserves the elements added to the vector. Elementdata is a dynamic array, assuming that when the vector is initialized, the > size of the dynamic array is not specified. The default size of 10 is used. As the elements in the vector are added, the vector's capacity also increases dynamically. Capacityincrement is the growth factor associated with capacity growth.

(2) Elementcount is the actual size of the dynamic array.

(3) Capacityincrement is the growth factor of the dynamic array. Assume that the size of the capacityincrement is specified when the vector is created. Then, each time when the dynamic array capacity of the vector is added >. The added size is capacityincrement.

Three, all methods and descriptive narration

1 void Add (Intindex, Object Element)

Inserts the specified element into the specified position at this vector.

2 Booleanadd (Object o)

Joins the specified element to the end of this vector.

3 Booleanaddall (Collection c)

Appends all the elements in the specified collection to the end of this vector. Because they are by the specified collection?? The order in which the iterators are returned.

4 booleanaddall (int index, Collection c)

Inserts all the elements in the specified collection to the specified position in this vector.

5 voidaddelement (Object obj)

The specified component is added to the end of this vector, and its size is appended.

6 int Capacity ()

Returns the current capacity of this vector.

7 Voidclear ()

Removes all elements from this vector.

8 Object Clone ()

Returns a copy of this vector.

9 Booleancontains (Object elem)

Assume that a test specifies the object of the component in this vector.

Ten Booleancontainsall (Collection c)

Returns true if this vector includes all elements in the specified collection.

Voidcopyinto (object[] anarray)

Copies the component of this vector to the specified array.

Objectelementat (int index)

Returns the component at the specified index.

Enumerationelements ()

Returns an enumeration of the components of this vector.

voidensurecapacity (int mincapacity)

The capacity of this vector is added, assuming that it is necessary to ensure that it can hold the minimum number of parameters specified by the minimum size of the component.

Booleanequals (Object o)

Specifies the equality of the object with this vector.

Objectfirstelement ()

Returns the first component of this vector (the item at index 0).

Objectget (int index)

Returns the element at the specified position in this vector.

Inthashcode ()

Returns the hash code value for this vector.

Intindexof (Object elem)

Searches for a given number of parameters, using the Equals method to test the first occurrence of an equal element.

Intindexof (Object elem, int index)

Searches for a given number of parameters, starts the search index, and tests for the first occurrence of equality using the Equals method.

Voidinsertelementat (Object obj, int index)

Specifies that the object is inserted into the component at the specified index in this vector.

Booleanisempty ()

Let's say whether this vector does not include components.

Objectlastelement ()

Returns the last component of this vector.

Intlastindexof (Object elem)

Returns the index of the last occurrence of the specified object for this vector.

Intlastindexof (Object elem, int index)

Searches backward for the specified object. Starts at the specified index and returns its subscript.

Objectremove (int index)

Removes the element at the specified position in the vector.

Booleanremove (Object o)

The first match of the specified element in this vector is removed, assuming that the vector does not include the element. It is unchanged.

Booleanremoveall (Collection c)

All elements that remove this vector are included in the specified collection.

Voidremoveallelements ()

Remove all components from this vector and set its size to zero.

Booleanremoveelement (Object obj)

Deletes the first (least-indexed) match from this vector's number of references.

Voidremoveelementat (int index)

Removeelementat (int index)

Protectedvoid removerange (int fromIndex, int toindex)

Removes all indexes for FROMINDEX (inclusive) and toindex, exclusive elements from this list.

Booleanretainall (Collection c)

Holds only elements that are included in the specified collection in this vector.

Objectset (int index, Object Element)

Replaces the element in the specified position with the specified element at this vector.

Voidsetelementat (Object obj, int index)

Sets the specified object at the specified index of the vector.

voidsetsize (int newSize)

Sets the size of this vector.

Panax Notoginseng intsize ()

Returns the number of components in this vector.

listsublist (int fromIndex, int toindex)

Return to Fromindex (inclusive) and toindex, and enjoy the list part view.

Object[]toarray ()

Returns an array that includes all elements in this vector in the correct order.

Object[]toarray (object[] a)

Returns an array that includes all elements in the correct order in this vector; the execution-time type of the returned array is the specified array.

Stringtostring ()

Returns the string representation of this vector. This includes a string representation of each element.

Voidtrimtosize ()

This fine-tuning, vector is the current size of the vector's capacity.

Attention:

(1) Vectors actually store data through an array. When we construct VECOTR. If you use the default constructor. The vector's default capacity size is 10.

(2) Vector capacity is added when vector capacity is insufficient to accommodate all elements.

If the capacity adds a factor of >0, the value of capacity is added as "capacity add factor"; Add the capacity size one times.

(3) Vector cloning function. That is, all the elements are cloned into an array.

Iv. Demonstration Examples:

<span style= "FONT-SIZE:18PX;" >importjava.util.Vector;importjava.util.List;importjava.util.Iterator;importjava.util.Enumeration;  /** * @desc vector test function: traverse vector and frequently use API * * @author Skywang */public classvectortest {public static void main (string[]                   args) {//new vector vector Vec = new vector ();        add Element Vec.add ("1");        Vec.add ("2");        Vec.add ("3");        Vec.add ("4");         Vec.add ("5");        Set the first element to Vec.set (0, "100");       Insert "500" into the 3rd position Vec.add (2, "300");         System.out.println ("VEC:" +vec);        (Sequential lookup) Gets the index of the 100 System.out.println ("Vec.indexof": "+vec.indexof (" 100 "));        (Reverse lookup) gets the index of 100 System.out.println ("Vec.lastindexof": "+vec.lastindexof (" 100 "));        Gets the first element of the System.out.println ("Vec.firstelement ():" +vec.firstelement ());        Gets the 3rd element of System.out.println ("Vec.elementat (2):" +vec.elementat (2)); Gets the last element System.out.println ("Vec.lastElement (): "+vec.lastelement ());        Gets the size of the vector System.out.println ("Size:" +vec.size ());         Get the total capacity of the vector System.out.println ("Capacity:" +vec.capacity ());         Gets the "2nd" to "4th" elements of the vector System.out.println ("Vec 2 to4:" +vec.sublist (1, 4));        Traverse Vector Enumeration ENU = Vec.elements () via enumeration;                   while (Enu.hasmoreelements ()) System.out.println ("Nextelement ():" +enu.nextelement ());        Vector Retainvec = new vector ();        Retainvec.add ("100");        Retainvec.add ("300");       Gets the collection of "Retainvec elements" included in "Vec" System.out.println ("Vec.retain ():" +vec.retainall (Retainvec));                   System.out.println ("VEC:" +vec);        Get VEC corresponding String array string[] arr = (string[]) Vec.toarray (new string[0]);         for (String Str:arr) System.out.println ("str:" +STR); Empty the vector.        Clear () is the same as removeallelements ().         Vec.clear ();//vec.removeallelements (); Infer if the vector is empty       System.out.println ("Vec.isempty ():" +vec.isempty ()); }} vec:[100, 2, 300,3, 4, 5]vec.indexof (+): 0vec.lastindexof (+): 0vec.firstelement (): 100vec.elementat (2) : 300vec.lastelement (): 5size:6capacity:10vec 2 to 4:[2,300, 3]nextelement (): 100nextElement (): 2nextElement () : 300nextElement (): 3nextElement (): 4nextElement (): 5vec.retain (): truevec:[100, 300]str:100str:300vec.isempty (): True</span>

Vi. differences between vectors and ArrayList in Java

First of all, both classes implement the list interface, and the list interface has three implementation classes together. Each is ArrayList, vector and LinkedList. The list is used to hold multiple elements. The order of elements can be maintained. and agree to the repetition of the elements. The related differences between the 3 detailed implementation classes are as follows:

ArrayList is the most frequently used list implementation class, implemented internally by arrays, and it agrees to high-speed random access to elements. The disadvantage of an array is that there can be no interval between each element, and when the array size does not meet the need to add storage capacity, it is necessary to copy the data of the array into the new storage space. When inserting or deleting an element from the middle of a ArrayList, it is necessary to copy, move, and cost the array. Therefore, it is suitable for random lookups and traversal, and is not suitable for insertions and deletions.

Vectors, like ArrayList, are also implemented through arrays, but the difference is that it supports thread synchronization. That is, there is only one thread at a time that can write vectors. Avoid inconsistencies caused by multithreading at the same time, but achieving synchronization requires very high costs, so it's slower to visit than to ask ArrayList.

LinkedList is used to store data in a linked list structure. Very suitable for dynamic insertion and deletion of data, random access and traversal speed is slower. In addition, he provides methods that are not defined in the list interface, specifically for manipulating the header and footer elements, and can be used as stacks, queues, and bidirectional queues.

about ArrayList and vector differences such as the following:

ArrayList default is 50% + 1 when memory is insufficient. Vector is 1 time times the default extension.

The vector provides the indexof (obj, start) interface, ArrayList not.

The vector is at the thread-safe level. However, in most cases, vectors are not used, because thread safety requires much more overhead.

V: Topics in the vector class of Java

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.