Programming with Java, part 4

記事
IT・テクノロジー

1.About List of collection class

I will talk about frequently used collection classes from the
utility "java.util" provided by Java. This time about List.
In the List, the elements are arranged in order.
If you want to use an array, you need to specify the number
of elements in advance, but in the case of List, you can use
List without specifying it.

There are two types of List, "ArrayList" and "LinkedList".
The program below uses ArrayList.

------------------------- ListTest.java -----------------------------------------
import java.util.*;

public class ListTest {
 public static void main(String args[]) throws Exception{
  ArrayList<String> list = new ArrayList<String>();

  // Measurement starts.
  long startTime_add = System.currentTimeMillis();
  for(int i=0; i<1000000; i++) {
   list.add(String.valueOf(i));
  }

  // Measurement ends.
  long endTime_add = System.currentTimeMillis();
  System.out.println("Add time(ms):" + (endTime_add - startTime_add));

  // Measurement starts.
  long startTime_get = System.currentTimeMillis();
  String tmp = list.get(500000);

  // Measurement ends.
  long endTime_get = System.currentTimeMillis();
  System.out.println("Get time(ms):" + (endTime_get - startTime_get));
  System.out.println("Get item:" + tmp);
 }
}
-------------------------------------------------------------------------------------

First of all, "import java.util. *;" Is required when you use ArrayList.
Then, it is made into an object by the line
"ArrayList<String> list = new ArrayList<String>();". This time,
I wrote "<String>" because the data of String class is handled
by List. If it is a number, write it as <Integer>. However,
basic data types such as int and long are not good. Please note
that the data handled by List is limited to classes.

Also, this time, I have measured the processing time in
milliseconds.
・Time taken to add 1 million data to list
・Time taken to get data from the 500,000th list
I have examined these two, and I will show you the results later.


Next, the following program uses LinkedList.

------------------------- ListTest2.java ----------------------------------------
import java.util.*;

public class ListTest2 {
 public static void main(String args[]) throws Exception{
  LinkedList<String> list = new LinkedList<String>();

  // Measurement starts.
  long startTime_add = System.currentTimeMillis();
  for(int i=0; i<1000000; i++) {
   list.add(String.valueOf(i));
  }

  // Measurement ends.
  long endTime_add = System.currentTimeMillis();
  System.out.println("Add time(ms):" + (endTime_add - startTime_add));

  // Measurement starts.
  long startTime_get = System.currentTimeMillis();
  String tmp = list.get(500000);

  // Measurement ends.
  long endTime_get = System.currentTimeMillis();
  System.out.println("Get time(ms):" + (endTime_get - startTime_get));
  System.out.println("Get item:" + tmp);
 }
}
-------------------------------------------------------------------------------------

As you can see, all the other processing is the same, 
just having changed the ArrayList to the LinkedList.
In both lists, you add elements with the add method and
retrieve elements with the get method. The difference is
the method lists have. The add method adds an element to
the end of the list, but the LinkedList has an addFirst method
that allows you to add an element to the beginning of the list.
On the other hand, ArrayList does not have an addFirst method.
However, it is possible to add an element to the beginning of
the ArrayList by specifying the insertion position in the
parameter of the add method. There are other method
differences, but I will omit them.


Next, let's see the measurement result of the processing time.


PC performance
・32bit Windows
・AMD Athlon(tm) Ⅱ X2 215 Processor 2.70GHz
・Memory(RAM):2GB

Result(Average of 5 times measurements)
①ArrayList
1 million data registration:502 ms
Acquisition of 500,000th data:0 ms(Less than a millisecond)

②LiskedList
1 million data registration:774 ms
Acquisition of 500,000th data:18 ms


ArrayList was faster in case of adding data like this time.
If you repeatedly delete or add data, the results may change.
Data acquisition was also faster with ArrayList. Since
LiskedList refers to each element with a bidirectional link,
the number of references may have increased by the time
it reaches the 500,000th item.


2.Main uses of List

List can be used in various situations. And List is especially
useful in situations where the result of SELECT from DB is
handled, so I think you should understand. For example,
suppose you build a grade table in the DB as shown below.

2.png

Next, you define the class in "Grade.java" for handling
the data for one record of the Grade table. This is called
an entity class. You define its member variables as follows.
・private String studentNumber;
・private String name;
・private Integer language;
・private Integer math;
・private Integer class;
Also prepare each getter and setter. After the SELECT result
is stored in the list, it is processed as follows.

    for(int i=0; i<list.size(); i++) {
        Grade grade = list.get(i);
        String strNumber = grade.getStudentNumber();
                    ・
                    ・
                    ・
    }

By using the number of elements in list like this, you can
retrieve data one record at a time.


[Japanese]

1.コレクションクラスのListについて

Javaが提供しているユーティリティ「java.util」の中から、よく利用するコレクションクラスについてお話します。今回はListについてです。
Listは、要素が順序を持って並んでいます。もし配列を使用する場合は、予め要素数(配列に格納する部屋の数)を指定する必要がありますが、Listの場合は指定せずに使用できます。

Listには「ArrayList」と「LinkedList」の2種類があります。下記のプログラムは、ArrayListを利用したものです。

------------------------- ListTest.java -----------------------------------------
import java.util.*;

public class ListTest {
 public static void main(String args[]) throws Exception{
  ArrayList<String> list = new ArrayList<String>();

  // Measurement starts.
  long startTime_add = System.currentTimeMillis();
  for(int i=0; i<1000000; i++) {
   list.add(String.valueOf(i));
  }

  // Measurement ends.
  long endTime_add = System.currentTimeMillis();
  System.out.println("Add time(ms):" + (endTime_add - startTime_add));

  // Measurement starts.
  long startTime_get = System.currentTimeMillis();
  String tmp = list.get(500000);

  // Measurement ends.
  long endTime_get = System.currentTimeMillis();
  System.out.println("Get time(ms):" + (endTime_get - startTime_get));
  System.out.println("Get item:" + tmp);
 }
}
-------------------------------------------------------------------------------------

まずは、ArrayListを使用する場合は「import java.util.*; 」が必要です。続いて、「ArrayList<String> list = new ArrayList<String>(); 」の行でオブジェクト化しています。今回はStringクラスのデータをListで扱うため、「<String>」と書きました。数値なら<Integer>のように書きます。ただし、intやlongなどの基本データ型はNGです。Listで扱うデータはクラスに限られていますので、注意しましょう。

また、今回は処理時間をミリ秒単位で計測しています。
・Listに100万個のデータを追加してかかった時間
・Listの50万個目からデータを取得するのにかかった時間
の2つを調べてみましたので、後ほどその結果をお見せします。


続いて、LinkedListを利用したのが下記のプログラムです。

------------------------- ListTest2.java ----------------------------------------
import java.util.*;

public class ListTest2 {
 public static void main(String args[]) throws Exception{
  LinkedList<String> list = new LinkedList<String>();

  // Measurement starts.
  long startTime_add = System.currentTimeMillis();
  for(int i=0; i<1000000; i++) {
   list.add(String.valueOf(i));
  }

  // Measurement ends.
  long endTime_add = System.currentTimeMillis();
  System.out.println("Add time(ms):" + (endTime_add - startTime_add));

  // Measurement starts.
  long startTime_get = System.currentTimeMillis();
  String tmp = list.get(500000);

  // Measurement ends.
  long endTime_get = System.currentTimeMillis();
  System.out.println("Get time(ms):" + (endTime_get - startTime_get));
  System.out.println("Get item:" + tmp);
 }
}
-------------------------------------------------------------------------------------

見ての通り、ArrayListをLinkedListに変えただけで、他の処理は全て同じです。どちらのListもaddメソッドで要素を追加したり、getメソッドで要素を取り出したりします。違いは、所有しているメソッドです。addメソッドはListの最後に要素を追加しますが、LinkedListにはaddFirstメソッドがあり、Listの先頭に要素を追加できます。一方のArrayListにはaddFirstメソッドがありません。ですが、addメソッドのパラメータに挿入位置を指定することで、Listの先頭に要素を追加することは可能です。他にもメソッドの違いはありますが、省略します。

次は、処理時間の計測結果を見てみましょう。


計測したパソコンの性能
・32ビット Windows
・AMD Athlon(tm) Ⅱ X2 215 Processor 2.70GHz
・実装メモリ(RAM):2GB

計測結果(5回の計測の平均)
①ArrayListクラス
100万個のデータ登録:502 ms
50万個目のデータ取得:0 ms(1ミリ秒未満)

②LiskedListクラス
100万個のデータ登録:774 ms
50万個目のデータ取得:18 ms


今回のように、単純にデータを追加しただけでは、ArrayListの方が速かったです。もし、データの削除や登録を繰り返した場合は、結果が変わるかもしれません。データ取得もArrayListの方が速かったです。LiskedListは要素同士を双方向のリンクで参照していますので、50万個目に辿り着くには参照回数が多くなってしまったのかもしれません。


2.Listの主な用途

様々な場面でListを利用できますが、DBからSELECTした結果を扱う場面は特にListが重宝しますので、理解しておいた方が良いだろうと思います。例えば、DBに下図のような成績テーブルを構築したとします。

1.png


次に、成績テーブルの1レコード分のデータを扱うためのクラスを、
仮に「Grade.java」に定義しましょう。これをエンティティクラスといいます。そのメンバ変数は
・private String studentNumber;
・private String name;
・private Integer language;
・private Integer math;
・private Integer class;
のように定義し、それぞれのgetterとsetterも用意します。SELECTした結果が変数listに格納された後に、
    for(int i=0; i<list.size(); i++) {
        Grade grade = list.get(i);
        String strNumber = grade.getStudentNumber();
                    ・
                    ・
                    ・
    }
のように変数listの要素数でループすれば、1レコードずつデータを取り出すことができるのです。
サービス数40万件のスキルマーケット、あなたにぴったりのサービスを探す