java集合類——ArayListとVector類
ArayList:APIを見ると、ArayListがListインターフェースを実現することがわかる。
ArayListのsize()法で得られたのは、実際の要素の個数であり、オブジェクトを生成する際の初期サイズにかかわらず、自動的に最適化される。ArayListは、foreachとIteratorを使用して出力することができます。スレッドが安全ではありません。コードは以下の通りです
VectorはIterator、foreach、Enumerationを使って出力することができます。即ち元素を得ることができます。
ArayListのsize()法で得られたのは、実際の要素の個数であり、オブジェクトを生成する際の初期サイズにかかわらず、自動的に最適化される。ArayListは、foreachとIteratorを使用して出力することができます。スレッドが安全ではありません。コードは以下の通りです
package ArrayListVectorTest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ArrayListTest {
/**
* @param args
*/
public static void main(String[] args) {
List<String> strs = new ArrayList<String>(4);
System.out.println(strs.size());
String str1 = "hello";
String str2 = "world";
strs.add(str2);
strs.add(str1);
System.out.println(strs.size());
print(strs);
}
private static void print(List<String> strs) {
for(String str : strs) {
System.out.print(str + " ");
}
System.out.println();
System.out.println("------------------------------");
Iterator<String> strIterator = strs.iterator();
for(;strIterator.hasNext();) {
System.out.print(strIterator.next() + " ");
}
System.out.println();
System.out.println("------------------------------");
}
}
出力:0
2
world hello
------------------------------
world hello
------------------------------
ArayListはまだたくさんの操作があります。文書の中で具体的な使い方を探すことができます。VectorはIterator、foreach、Enumerationを使って出力することができます。即ち元素を得ることができます。
package ArrayListVectorTest;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
public class VectorTest {
/**
* @param args
*/
public static void main(String[] args) {
Vector<String> strs = new Vector<String>(4);
System.out.println(strs.size());
String str1 = "hello";
String str2 = "world";
strs.add(str1);
strs.add(str2);
System.out.println(strs.size());
print(strs);
}
private static void print(Vector<String> strs) {
for(String str : strs) {
System.out.print(str + "");
}
System.out.println();
System.out.println("--------------------");
Iterator<String> strIterator = strs.iterator();
for(;strIterator.hasNext();) {
System.out.print(strIterator.next() + " ");
}
System.out.println();
System.out.println("---------------------");
Enumeration<String> strEnum = strs.elements();
for(;strEnum.hasMoreElements();) {
System.out.print(strEnum.nextElement());
}
System.out.println();
System.out.println("-----------------------");
}
}
出力:0
2
helloworld
--------------------
hello world
---------------------
helloworld
-----------------------
全体として、アラーリストとVectorの違いは小さいです。多くの方法は同じです。