java中Vector的簡單使用

來源:互聯網
上載者:User

和C++中的vector類似,也是可以儲存各種類型的元素。

引入包import  java.util.Vector;


eg.

Vector ivec = new Vector();

Vector ivec = new Vector(10);           //初始長度為10的ivec

Vector ivec = new Vector(10, 5);       //初始長度為10,當空間不夠需要增長時增長長度為5


ivec.add(5);                                        //添加元素5

ivec.add(int index,  Object value);  //在index位置添加元素value,插入後,其他元素後移

ivec.set(int index,  Object  value);   //索引為index的元素值更改為value

Object  obj = ivec.get(int index);    //獲得索引為index的元素的值

ivec.remove(int index);                     //刪除索引為index的元素,刪除後,後面元素前移

ivec.toString();                                   //把所有元素轉換成字串輸出


和C++中的vector刪除所有元素時都需要注意的是:C++中刪除元素會使得迭代器失效,如下:

for(std::vector<int>::iteator iter = vec.begin();  iter != vec.end(); ++ iter)

{

    vec.erase(iter);                //錯誤! 這樣不會正確刪除所有元素

}

之所以不能正確刪除所有元素,是因為vec.erase(iter)後迭代器失效,應該用下面的方式寫:

for(std::vector<int>::iteator iter = vec.begin();  iter != vec.end();   )

{

    if(條件)

    {

        iter = vec.erase(iter);         //儲存每次迭代器的值,刪除後iter指向下一個待刪除元素

    }

    else

    {

        ++ iter;

    }

}

類似的,在java中刪除所有元素時如下:

for(int i = 0; i < ivec.size();  )

{

    ivec.remove(i);                  //或者ivec.remove(0);

}



System.out.println("以字串形式輸出所有元素:" + ivec.toString());



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.