目次
序文
一、Objectクラス
- toString()メソッド
- equals(Object obj)メソッド
- clone() メソッド
二、Objectsユーティリティクラス
三、プリミティブ型ラッパークラス
- ラッパーインスタンスの生成方法
- データ型変換処理
四、StringBuilderクラス
- StringBuilderメソッドの実演
- StringBuilder実践応用例
五、StringJoinerクラス
六、Mathクラス
七、Systemクラス
八、Runtimeクラス
九、BigDecimalクラス
十、Dateクラス
十一、SimpleDateFormatクラス
十二、Calendarクラス
十三、JDK8新規日付時刻クラス群
- JDK8日付クラス導入の背景
- JDK8日付・時刻・日時表現
- JDK8タイムゾーン対応
- JDK8Instantクラス
- JDK8日付フォーマット処理
- JDK8期間計算Periodクラス
- JDK8時間差算出Durationクラス
十四、Arraysクラス
- Arrays基本操作
- オブジェクト配列の処理
序文
この章では、Javaプログラミングにおける基本的なAPI群を体系的に学習します。API(Application Programming Interface)とは、Javaが提供する既存のプログラム機能であり、クラスやメソッドなどを指します。これらのAPIを活用することで、問題解決を効率的に行うことができます。
JavaSEの核となるAPI群をマスターすることで、より高度な開発スキルを習得できます。多くの初心者がAPIの学習において「理解はできるが記憶できない」という課題に直面します。重要なのは継続的な実践とコード書き込みです。
一、Objectクラス
ObjectクラスはJavaにおけるすべてのクラスの親クラスです。したがって、JavaのすべてのオブジェクトはObjectクラスのメソッドを利用できます。
1. toString()メソッド
toString()メソッドは、オブジェクトの文字列表現を返却します。デフォルト形式は「パッケージ名.クラス名@ハッシュ値(16進数)」です。
例として、Personクラスを作成します:
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{姓名='" + name + "', 年齢=" + age + "}";
}
}
テストコード:
public class Example {
public static void main(String[] args) {
Person person = new Person("李明", 25);
System.out.println(person.toString());
}
}
2. equals(Object obj)メソッド
equalsメソッドは、現在のオブジェクトと引数のオブジェクトが「等しい」かどうかを判定します。デフォルトでは参照比較を行います。
Personクラスでequalsメソッドをオーバーライド:
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person person = (Person) obj;
if (age != person.age) return false;
return name != null ? name.equals(person.name) : person.name == null;
}
3. clone() メソッド
clone()メソッドは、現在のオブジェクトの複製を作成し返却します。クローン対象のクラスはCloneableインターフェースを実装する必要があります。
public class DataRecord implements Cloneable {
private String identifier;
private String userName;
private String password;
private double[] results;
public DataRecord(String identifier, String userName, String password, double[] results) {
this.identifier = identifier;
this.userName = userName;
this.password = password;
this.results = results;
}
@Override
protected Object clone() throws CloneNotSupportedException {
DataRecord record = (DataRecord) super.clone();
record.results = this.results.clone();
return record;
}
}
二、Objectsユーティリティクラス
Objectsクラスは、オブジェクト操作に関する静的メソッドを提供するユーティリティクラスです。
public class Example {
public static void main(String[] args) {
String text1 = null;
String text2 = "example";
System.out.println(Objects.equals(text1, text2)); // null安全な比較
System.out.println(Objects.isNull(text1)); // nullチェック
System.out.println(Objects.nonNull(text2)); // 非nullチェック
}
}
三、プリミティブ型ラッパークラス
Javaの8つの基本データ型をオブジェクトとして扱うために、それぞれに対応するラッパークラスが存在します。
1. ラッパーインスタンスの生成方法
自動ボックス化とアンボックス化の例:
Integer number = 100; // 自動ボックス化
int primitive = number; // 自動アンボックス化
// 明示的な生成方法
Integer boxed = Integer.valueOf(200);
Integer legacy = new Integer(300); // 非推奨
2. データ型変換処理
文字列と数値の相互変換:
// 文字列から数値への変換
String numericStr = "123";
int convertedInt = Integer.parseInt(numericStr);
double convertedDouble = Double.parseDouble("45.67");
// 数値から文字列への変換
String result = Integer.toString(convertedInt);
String altResult = String.valueOf(convertedInt);
四、StringBuilderクラス
StringBuilderは可変長文字列を扱うためのクラスで、文字列操作の効率を向上させます。
1. StringBuilderメソッドの実演
public class Example {
public static void main(String[] args) {
StringBuilder buffer = new StringBuilder("初期文字列");
buffer.append("追加").append(123).append(true);
buffer.reverse();
System.out.println(buffer.toString());
System.out.println("長さ: " + buffer.length());
}
}
2. StringBuilder実践応用例
整数配列を指定形式の文字列に変換:
public static String convertArrayToString(int[] inputArray) {
if (inputArray == null) return null;
StringBuilder builder = new StringBuilder("[");
for (int i = 0; i < inputArray.length; i++) {
if (i == inputArray.length - 1) {
builder.append(inputArray[i]).append("]");
} else {
builder.append(inputArray[i]).append(",");
}
}
return builder.toString();
}
五、StringJoinerクラス
StringJoinerは文字列結合を簡潔に行えるクラスです。
StringJoiner joiner = new StringJoiner(",", "[", "]");
joiner.add("要素1").add("要素2").add("要素3");
System.out.println(joiner.toString()); // [要素1,要素2,要素3]
六、Mathクラス
Mathクラスは数学計算用の静的メソッドを提供します。
System.out.println(Math.abs(-45)); // 絶対値
System.out.println(Math.max(10, 20)); // 最大値
System.out.println(Math.pow(2, 3)); // べき乗
System.out.println(Math.sqrt(16)); // 平方根
System.out.println(Math.random()); // 乱数生成
七、Systemクラス
Systemクラスはシステム関連のメソッドを提供します。
long startTime = System.currentTimeMillis();
// 処理実行
long endTime = System.currentTimeMillis();
System.out.println("実行時間: " + (endTime - startTime) + "ms");
八、Runtimeクラス
RuntimeクラスはJVMの実行環境情報を取得できます。
Runtime runtime = Runtime.getRuntime();
System.out.println("CPUコア数: " + runtime.availableProcessors());
System.out.println("総メモリ: " + runtime.totalMemory() / (1024 * 1024) + "MB");
九、BigDecimalクラス
BigDecimalは高精度な数値計算を実現するクラスです。
BigDecimal valueA = BigDecimal.valueOf(0.1);
BigDecimal valueB = BigDecimal.valueOf(0.2);
BigDecimal sum = valueA.add(valueB);
System.out.println(sum); // 0.3
// 除算時の丸め処理
BigDecimal division = valueA.divide(valueB, 2, RoundingMode.HALF_UP);
十、Dateクラス
Dateクラスは日付時刻を表すためのクラスです。
Date currentDate = new Date();
System.out.println(currentDate);
long timestamp = currentDate.getTime();
十一、SimpleDateFormatクラス
SimpleDateFormatは日付の書式変換を担当します。
SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date now = new Date();
String formatted = formatter.format(now);
System.out.println(formatted);
十二、Calendarクラス
Calendarクラスは日付操作の拡張機能を提供します。
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1; // 0始まりのため+1
calendar.add(Calendar.DAY_OF_MONTH, 10); // 10日後
十三、JDK8新規日付時刻クラス群
1. JDK8日付クラス導入の背景
旧来のDateクラスはスレッドセーフでないなどの問題がありました。
2. JDK8日付・時刻・日時表現
LocalDate(日付のみ)、LocalTime(時刻のみ)、LocalDateTime(日時)に分類されます。
LocalDateTime current = LocalDateTime.now();
LocalDate dateOnly = LocalDate.now();
LocalTime timeOnly = LocalTime.now();
3. JDK8タイムゾーン対応
ZonedDateTimeはタイムゾーン情報を含む日時を扱います。
4. JDK8Instantクラス
Instantはエポックからの経過時間をナノ秒単位で表現します。
5. JDK8日付フォーマット処理
DateTimeFormatterはJDK8以降のフォーマット処理を担当します。
6. JDK8期間計算Periodクラス
Periodは日付間の年月日差を計算します。
7. JDK8時間差算出Durationクラス
Durationは時間間の時分秒差を計算します。
十四、Arraysクラス
Arraysクラスは配列操作のためのユーティリティクラスです。
1. Arrays基本操作
int[] array = {5, 2, 8, 1, 9};
Arrays.sort(array);
System.out.println(Arrays.toString(array));
int[] partialCopy = Arrays.copyOfRange(array, 1, 4);
2. オブジェクト配列の処理
ComparableインターフェースまたはComparatorによる並び替え:
Arrays.sort(objectArray, new Comparator<MyClass>() {
@Override
public int compare(MyClass a, MyClass b) {
return a.getProperty().compareTo(b.getProperty());
}
});