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的大小,多余的元素被抛弃 } }
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]
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); }
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); } }
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!

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

Java requires specific configuration and tuning on different platforms. 1) Adjust JVM parameters, such as -Xms and -Xmx to set the heap size. 2) Choose the appropriate garbage collection strategy, such as ParallelGC or G1GC. 3) Configure the Native library to adapt to different platforms. These measures can enable Java applications to perform best in various environments.

OSGi,ApacheCommonsLang,JNA,andJVMoptionsareeffectiveforhandlingplatform-specificchallengesinJava.1)OSGimanagesdependenciesandisolatescomponents.2)ApacheCommonsLangprovidesutilityfunctions.3)JNAallowscallingnativecode.4)JVMoptionstweakapplicationbehav

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

Java code can run on different operating systems without modification, because Java's "write once, run everywhere" philosophy is implemented by Java virtual machine (JVM). As the intermediary between the compiled Java bytecode and the operating system, the JVM translates the bytecode into specific machine instructions to ensure that the program can run independently on any platform with JVM installed.

The compilation and execution of Java programs achieve platform independence through bytecode and JVM. 1) Write Java source code and compile it into bytecode. 2) Use JVM to execute bytecode on any platform to ensure the code runs across platforms.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
