天天看點

java vector 使用 - youxin

java vector 使用

2012-12-02 00:13 

youxin 

閱讀(401) 

評論(0) 

編輯 

收藏 

舉報

建立一個一維的vector:

Vector<Double> v=new Vector<Double>();//執行個體一個v對象

v.addElement();//在v中添加元素的方法

v.elementAt(i);//取得v中索引為i的元素

c++的 vector使用不需要new

vector<int> v(10);

vector向末尾添加元素有2種方法,add和addElement,有什麼差別呢?

add()

 comes from the 

List

 interface, which is part of the Java Collections Framework added in Java 1.2.

Vector

 predates that and was retrofitted with it. The specific differences are:

  1. addElement()

     is 

    synchronized

    add()

     isn\'t. In the Java Collections Framework, if you want these methods to be synchronized wrap the collection in 

    Collections.synchronizedList()

    ; and
  2. add()

     returns a boolean for success. 

    addElement()

     has a 

    void

     return type.

The 

synchronized

 difference technically isn\'t part of the API. It\'s an implementation detail.

Favour the use of the 

List

 methods. Like I said, if you want a 

synchronized

List

 do:

List<String> list =Collections.synchronizedList(newArrayList<String>());
list.add("hello");
via:http://stackoverflow.com/questions/3089969/difference-between-javas-vector-add-and-vector-addelement
差別基本可以忽略。

vector建立2維數組:
           

Vector<Vector<Double>> v=

new

Vector<Vector<Double> >();

//Example: get(0,2)

Double d=v.get(

).get(

2

);

new <? >表示泛型。

從jdk5.0開始,新增了泛型功能。泛型可以使把你的定義的對象置于某個容器而不失去其類型。也可以定義泛型類,public class classname <T> {}

  • 分類 Java
java vector 使用 - youxin