Java Vector addElement()
Java Vector 类的
addElement()方法用于添加指定的元素到此向量的末尾。添加一个元素会使Vector 大小增加一。
语法:
以下是
addElement()方法的声明:
Public void addElement(E e)
参数:
参数 |
说明 |
必需/可选 |
e |
这是将添加到向量中的元素。 |
必需 |
返回:
addElement()方法不返回任何内容,因为其返回类型为
void 。
例外:
NA
兼容版本:
Java 1.2及更高版本
示例1:
import java.util.Vector;
public class VectorAddElementExample1 {
public static void main(String arg[]) {
//Create an empty Vector with an initial capacity of 3
Vector<String> vc = new Vector<>(3);
//Add elements in the vector by using add() method
vc.add("A");
vc.add("B");
vc.add("C");
//Print all the elements of a Vector
System.out.println("--Elements of Vector are--");
for (String str : vc) {
System.out.println("Element= " +str);
}
//Add new element
vc.addElement("lidihuo");
//After addition, print all the elements again
System.out.println("---Elements after addition--- ");
for (String str : vc) {
System.out.println("Element= " +str);
}
}
}
输出:
--Elements of Vector are--
Element= A
Element= B
Element= C
---Elements after addition---
Element= A
Element= B
Element= C
Element= lidihuo
示例2:
import java.util.Vector;
public class VectorAddElementExample2 {
public static void main(String arg[]) {
//Create an empty Vector with an initial capacity of 3
Vector<Integer> vc = new Vector<>(3);
//Add elements in the vector by using add() method
vc.add(101);
vc.add(-201);
vc.add(301);
//Print all the elements of a Vector
System.out.println("Elements of Vector are: "+vc);
//Add new element
vc.addElement(-5001);
//After addition, print all the elements again
System.out.println("Elements of vector after addition: "+vc);
}
}
输出:
Elements of Vector are: [101, -201, 301]
Elements of vector after addition: [101, -201, 301, -5001]