HOWTO · Java

Java の Vector と ArrayList

このチュートリアルでは、Java の Vector と ArrayList について説明します。

このページの内容

ArrayListVector はどちらも List インターフェイスを実装しており、どちらも内部データ構造の配列として使用できます。 しかし、それらはほとんど同じですが、違いがあります。

同期は、ArrayList と Vector の最も大きな違いです。 その中で、Vector は同期されます。つまり、一度にアクセスできるスレッドは 1つだけです。

一方、ArrayList は同期されません。 複数のスレッドが同時にアクセスできます。

ArrayListVector のパフォーマンスを比較すると、ArrayListVector よりもはるかに高速です。

ArrayList は同期できるため、ほとんどのプロのプログラマーは Vector の代わりに ArrayList の使用をサポートしています。

この記事では、ArrayListVector の使用について説明します。 また、トピックを簡単にするために必要な例と説明も表示されます。

Java の Vector と ArrayList

以下の例では、ArrayListVector の両方を示しています。 ArrayListVector の両方を宣言し、いくつかの要素を追加し、それらに追加した要素を出力します。

以下のサンプルコードを見てください。

// Importing necessary packages.

import java.io.*;
import java.util.*;

public class JavaArraylist {
  public static void main(String[] args) {
    // Creating an ArrayList with the type "String"
    ArrayList<String> MyArrayList = new ArrayList<String>();

    // Adding elements to arraylist
    MyArrayList.add("This is the first string element.");
    MyArrayList.add("This is the second string element.");
    MyArrayList.add("This is the third string element.");
    MyArrayList.add("This is the fourth string element.");

    // Traversing the elements using Iterator from the MyArrayList
    System.out.println("The arrayList elements are:");
    Iterator Itr = MyArrayList.iterator();
    while (Itr.hasNext()) System.out.println(Itr.next());

    // Creating a Vector with the type "String"
    Vector<String> MyVectorList = new Vector<String>();
    MyVectorList.addElement("Designing");
    MyVectorList.addElement("Planning");
    MyVectorList.addElement("Coding");

    // Traversing the elements using Enumeration from the MyVectorList
    System.out.println("\nThe Vector elements are:");
    Enumeration enm = MyVectorList.elements();
    while (enm.hasMoreElements()) System.out.println(enm.nextElement());
  }
}

コードを説明しましょう。 各行の目的についてはすでにコメントしました。

上記の例では、最初に MyArrayList という名前の ArrayList を作成し、次にいくつかの文字列要素を追加しました。 その後、Iterator を使用して MyArrayList のすべての要素を出力しました。

ここで、MyVectorList という名前の VectorList を作成しました。 次に、いくつかの文字列要素を追加し、Enumeration を使用して MyVectorList の要素を出力しました。

上記の例を実行すると、以下のような出力が得られます。

The arrayList elements are:
This is the first string element.
This is the second string element.
This is the third string element.
This is the fourth string element.

The Vector elements are:
Designing
Planning
coding

マルチスレッド プロジェクトで作業している場合は、ArrayList が最適なオプションです。

ここで共有されているコード例は Java であり、システムに Java が含まれていない場合は、環境に Java をインストールする必要があることに注意してください。