Home > Java > javaTutorial > body text

Summary of examples of vector class usage in Java

黄舟
Release: 2017-01-20 11:04:56
Original
1658 people have browsed it

The implementation of Vector and ArrayList are basically similar. They are also based on dynamic arrays and also need to be expanded. Here are three short examples to help you understand vector:

Basic operation examples

VectorApp.java

import java.util.Vector; 
import java.lang.*; 
import java.util.Enumeration; 
public class VectorApp 
{ 
  public static void main(String args[]) 
  { 
   Vector v1 = new Vector(); 
   Integer integer1= new Integer(1); 
   //加入为字符串对象 
   v1.addElement("one"); 
   //加入的为integer的对象 
   v1.addElement(integer1); 
   v1.addElement(integer1); 
   v1.addElement("two"); 
   v1.addElement(new Integer(2)); 
   v1.addElement(integer1); 
   v1.addElement(integer1); 
   //转为字符串并打印 
   System.out.println("The Vector v1 is:\n\t"+v1); 
   //向指定位置插入新对象 
   v1.insertElement("three",2); 
   v1.insertElement(new Float(3.9),3); 
   System.out.println("The Vector v1(used method 
   insertElementAt()is:\n\t)"+v1); 
   //将指定位置的对象设置为新的对象 
   //指定位置后的对象依次往后顺延 
   v1.setElementAt("four",2); 
   System.out.println("The vector v1 cused method setElmentAt()is:\n\t"+v1); 
   v1.removeElement(integer1); 
   //从向量对象v1中删除对象integer1 
   //由于存在多个integer1,所以从头开始。 
    //找删除找到的第一个integer1. 
   Enumeration enum = v1.elements(); 
   System.out.println("The vector v1 (used method removeElememt()is"); 
   while(enum.hasMoreElements()) 
   System.out.println(enum.nextElement()+""); 
   System.out.println(); 
   //使用枚举类(Enumeration)的方法取得向量对象的每个元素。 
    System.out.println("The position of Object1(top-to-botton):"+v1.indexOf(integer1)); 
   System.out.println("The position of Object1(tottom-to-top):"+v1.lastIndexOf(integer1)); 
   //按不同的方向查找对象integer1所处的位置 
    v1.setSize(4); 
   System.out.println("The new Vector(resized the vector)is:"+v1); 
   //重新设置v1的大小,多余的元素被抛弃  
  } 
}
Copy after login

Running results:

E:\java01>java VectorApp 
The vector v1 is:[one,1,1,two,2,1,1] 
The vector v1(used method insetElementAt()) is: 
[one,1,three,3.9,1,two,2,1,1] 
The vector v1(used method setElementAt()) is: 
[one,1,four,3.9,1,two,2,1,1] 
The vector v1(useed method removeElement()) is: 
one four 3.9 1 two 2 1 1 
The position of object1(top-to-botton):3 
The position of object1(botton-to-top):7 
The new Vector(resized the vector) is: 
[one,four,3.9,1]
Copy after login

Vertor’s 1x expansion
Do you remember that ArrayList is expanded to 0.5 times the size of the metaarray each time? Vector is slightly different from ArrayList when performing expansion operations

protected int capacityIncrement;//用于指定每次扩容的容量
 
private void grow(int minCapacity) {
 // overflow-conscious code
 int oldCapacity = elementData.length;
 int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
          capacityIncrement : oldCapacity);//如不指定capacityIncrement,默认扩容的容量为原数组的容量
 if (newCapacity - minCapacity < 0)
  newCapacity = minCapacity;
 if (newCapacity - MAX_ARRAY_SIZE > 0)
  newCapacity = hugeCapacity(minCapacity);
 elementData = Arrays.copyOf(elementData, newCapacity);
}
Copy after login

Careful friends can find that there is an additional capacityIncrement variable in Vector, which is used to specify the increment of each expansion. If this variable is not specified, In grow, you can find that Vector is expanded to 1 times the original array by default

Thread safety
Vertor is thread safe!
Another conspicuous thing in the Vertor source code is that most methods have the synchronized keyword. Everyone knows that this keyword is used for thread synchronization, so the Vector class is thread-safe!
But even if all its methods are modified to be synchronized, it does not mean that synchronization will never be needed when calling it:

private static Vector<Integer> vector=new Vector<Integer>();
public static void main(String[] args) { 
 while(true)
 {
 for(int i=0;i<10;i++)
 {
 vector.add(i);
 }
  
 Thread removeThread=new Thread(new Runnable(){
 @Override
 public void run()
 {
 for(int i=0;i<vector.size();i++)
 {
  vector.remove(i);
 }
 }
 });
  
 Thread printThread=new Thread(new Runnable(){
 @Override
 public void run()
 {
 for(int i=0;i<vector.size();i++)
 {
  System.out.println(vector.get(i));
 }
 }
 });
  
 removeThread.start();
 printThread.start();
  
 while(Thread.activeCount()>20);
  
 }
}
Copy after login

After everyone runs this code for a short period of time You will find an ArrayIndexOutOfBoundsException exception. Although the get, remove, and size methods of Vector are synchronized, in a multi-threaded environment, if no additional synchronization measures are taken on the method side, this code is still unsafe. If a thread deletes After getting the element with serial number i, if another thread accesses this i, an exception will be thrown directly. Therefore, to ensure the safety of this code, you need to add synchronized modification in the run.

The above is the use of vector class in Java The content of the sample summary, please pay attention to the PHP Chinese website (www.php.cn) for more related content!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!