Programming with Java, part 6

記事
IT・テクノロジー

1.Classes for character string

There are many situations where you handle characters.
Classes are provided in Java that are useful in such
cases, so I will introduce some of them.

(1)String

The first is the String class in the java.lang package.
When you use the class of java.lang package, it is not
necessary to write "import java.lang.*;". This is because
it is implicitly imported at compile.
Also, String can create an object without new.
    String strTmp = "test";
If you enclose the string in double quotes like this,
it will be treated as an object.

Next, I will introduce the methods that I often use in String.

①equals
Compares strings to each other and returns true if they match,
false if they don't. For example, use it as follows.

    String str1 = omitted
    String str2 = omitted
    if(str1.equals(str2)) {
        // Character strings match
    } else {
        // Mismatch
    }

②length
This returns the length of the string as an int type.

③contains
This returns true if the specified string is included,
false otherwise.

④substring
This is used when you want to extract a part
(partial character string) from a character string.

⑤replace
This is used when you replace a character string.

Besides these, String has many methods.


(2)StringBuffer

The second is the StringBuffer class in the same
java.lang package as String. String class has a fixed length,
but StringBuffer class has a variable length, so it is used
in situations where string concatenation is repeated.

    StringBuffer strBuf = new StringBuffer();

New in this way creates an empty string buffer with an
initial capacity of 16 characters. It is also possible to specify
the capacity as shown below.

    StringBuffer strBuf = new StringBuffer(256);

You use the append method when you want to concatenate
strings. For example, it is as follows.

    strBuf.append("ABC");
    strBuf.append("DEF");

Pass the string you want to add to the parameters of
the append method. Since the character string is always
added to the end, the character string of "ABCDEF" is
stored in strBuf after processing the above two lines.
If you want to use the character string stored in
StringBuffer as String type, use toString method.

   String strTmp = strBuf.toString();


2.Result of measuring processing time

You can concatenate strings with String class,
but you should avoid concatenating them frequently.
For concatenation, it is recommended to use StringBuffer.
Or StringBuilder which I did not introduce this time is good.
I measured the processing time (unit: milliseconds) to see
what kind of difference would occur when concatenating
character strings. The following is the program.

------------------------------ StringTest.java ----------------------------------
public class StringTest {
 public static void main(String args[]) throws Exception{
  String str = "";
  // Measurement starts.
  long startTime = System.currentTimeMillis();
  for(int i=0; i<1000; i++) {
   str = str + "a";
  }
  // Measurement ends.
  long endTime = System.currentTimeMillis();
  System.out.println("Time(ms):" + (endTime - startTime));
 }
}
-------------------------------------------------------------------------------------

----------------------------- StringTest2.java ----------------------------------
public class StringTest2 {
 public static void main(String args[]) throws Exception{
  StringBuffer str = new StringBuffer();
  // Measurement starts.
  long startTime = System.currentTimeMillis();
  for(int i=0; i<1000; i++) {
   str.append("a");
  }
  // Measurement ends.
  long endTime = System.currentTimeMillis();
  System.out.println("Time(ms):" + (endTime - startTime));
 }
}
-------------------------------------------------------------------------------------

Processing time when a character string is concatenated
1,000 times (average of 5 measurements)
String:12ms
StringBuffer:3ms

There was a difference in speed about 4 times. There may
be few situations where you concatenate 1,000 times, but
I think it is important to make program so that the
processing time is as short as possible.


[Japanese]

1.文字列を扱うクラスについて

文字を扱う場面は多々あります。そのような時に役立つクラスがJavaで提供されていますので、いくつか紹介します。

(1)String

1つ目は、java.langパッケージのStringクラスです。java.langパッケージのクラスを利用するときは、「import java.lang.*;」と書く必要はありません。コンパイル時に暗黙的にインポートされているからです。
また、Stringは、newしなくてもオブジェクトを作れます。
    String strTmp = "test";
このようにダブルクォーテーションで文字列を囲めば、オブジェクトとして扱われます。

続いて、Stringで私がよく使うメソッドを紹介します。

①equals
文字列と文字列を比較して、一致したらtrueを返し、一致しない場合はfalseを返します。例えば、
    String str1 = 省略
    String str2 = 省略
    if(str1.equals(str2)) {
        // 文字列が一致した場合の処理
    } else {
        // 不一致の場合の処理
    }
このように使います。

②length
文字列の長さをint型で返してくれます。

③contains
指定した文字列が含まれていればtrueを返し、含まれていなければfalseを返します。

④substring
文字列から一部(部分文字列)を取り出したいときに使います。

⑤replace
文字列を置換するときに使います。

この他にも、Stringは多くのメソッドを備えています。


(2)StringBuffer

2つ目は、Stringと同じjava.langパッケージのStringBufferクラスです。Stringは固定長なのですが、StringBufferは可変長ですので、文字列の連結を繰り返す場面で利用します。
    StringBuffer strBuf = new StringBuffer();
このようにnewすると、初期容量が16文字分の空の文字列バッファが作られます。下記のように容量を指定することも可能です。
    StringBuffer strBuf = new StringBuffer(256);

文字列を連結する場合は、appendメソッドを利用します。例えば、
    strBuf.append("ABC");
    strBuf.append("DEF");
このように、追加したい文字列をappendメソッドのパラメータに渡します。常に末尾に文字列が追加されますので、上記の2行を処理した後のstrBufには、"ABCDEF"の文字列が格納されています。
StringBuffer内に格納された文字列を、String型として利用したい場合は、
   String strTmp = strBuf.toString();
このようにtoStringメソッドを利用します。


2.処理時間の計測

Stringでも文字列の連結はできるのですが、頻繁に連結するのは避けた方が良いです。連結に関してはStringBufferや、今回は紹介しなかった
StringBuilderで行うことをおすすめします。
文字列の連結でどのような差が出るのか、処理時間(単位はミリ秒)を計測してみましたので、参考にしてみてください。下記が計測したプログラムです。

------------------------------ StringTest.java ----------------------------------
public class StringTest {
 public static void main(String args[]) throws Exception{
  String str = "";
  // Measurement starts.
  long startTime = System.currentTimeMillis();
  for(int i=0; i<1000; i++) {
   str = str + "a";
  }
  // Measurement ends.
  long endTime = System.currentTimeMillis();
  System.out.println("Time(ms):" + (endTime - startTime));
 }
}
-------------------------------------------------------------------------------------

----------------------------- StringTest2.java ----------------------------------
public class StringTest2 {
 public static void main(String args[]) throws Exception{
  StringBuffer str = new StringBuffer();
  // Measurement starts.
  long startTime = System.currentTimeMillis();
  for(int i=0; i<1000; i++) {
   str.append("a");
  }
  // Measurement ends.
  long endTime = System.currentTimeMillis();
  System.out.println("Time(ms):" + (endTime - startTime));
 }
}
-------------------------------------------------------------------------------------


文字列を1,000回連結したときの処理時間(5回の計測の平均)
String:12ms
StringBuffer:3ms

約4倍、速度に差がありました。1,000回も連結する場面は少ないかもしれませんが、なるべく処理時間がかからないようにプログラミングすることも重要だと思います。
サービス数40万件のスキルマーケット、あなたにぴったりのサービスを探す