Más contenido relacionado
La actualidad más candente (20)
Similar a Javaコーディング勉強会 (9)
Javaコーディング勉強会
- 5. 目次
第1部 基本編
第1章 本当は怖いString
鉄則1 文字列の連結にはStringBuilderを使う
鉄則2 文字列比較にはequals()メソッドを使う
第2章 知らなきゃ損!ビット演算
鉄則3 整数型の取りうる値の範囲を把握する
鉄則4 浮動小数点数のしくみをだいたい理解する
第3章 今さら聞けないプリミティブ型と参照型
鉄則5 プリミティブ型と参照型の違いを理解する
鉄則6 ボクシング・アンボクシングは最少にする
第4章 正しく使おう型のいろいろ
鉄則7 正しいコレクションの型を利用する
鉄則8 equals()、hashCode()メソッドを実装する
鉄則9 ストリームにはバッファを利用する
鉄則10 ストリームは必ずclose()する
鉄則11 例外を具体的な型でキャッチし処理する
第2部 応用編
第5章 あなたの書いたそのコード、読めますか?
鉄則12 メソッドの抽出で重複コードをまとめる
鉄則13 変数のインライン化で不要な変数を削除
鉄則14 説明変数を抽出して可読性を向上させる
鉄則15 変数名を変更して可読性を向上させる
鉄則16 マジックナンバーを定数に置き換える
鉄則17 ハードコード文字列を定数に置き換える
鉄則18 Javadocを記述する
まとめ リファクタリングショートカットキー
第3部 演習
総合演習 5
- 7. 鉄則1 文字列の連結にはStringBuilderを使う
だめな例:+で文字列を結合
public String connectSentence1(String[] wordArray) {
String sentence = "";
for (String word : wordArray) {
sentence += word + " ";
}
return sentence.trim();
}
public String connectSentence2(String[] wordArray) {
StringBuilder sentence = new StringBuilder();
for (String word : wordArray) {
sentence.append(word);
sentence.append(" ");
}
return sentence.toString().trim();
}
よい例:StringBuilder#appendメソッドで結合
7
- 8. 鉄則1 文字列の連結にはStringBuilderを使う
解説
String型オブジェクトは不変
String str = "a";
str += "b";
1003
“a”
1000
1001
1002
1003
1004
1005
1006
アドレス メモリ
str
イメージ
1003
“ab”
1000
1001
1002
1003
1004
1005
1006
アドレス メモリ
str 1003
“a”
1000
1001
1002
1003
1004
1005
1006
アドレス メモリ
str
辛い現実
1005
“a”
“ab”
“b”
1000
1001
1002
1003
1004
1005
1006
アドレス メモリ
str
多少事実と異なりますが、分かりやすくするために簡略化しています
連結するたびに新しいオブジェクトを生成
8
- 9. 鉄則1 文字列の連結にはStringBuilderを使う
連結を繰り返す場合にはStringBuilderによりメモリを節約する
String str = "a";
str += "b";
str += "c";
多少事実と異なりますが、分かりやすくするために簡略化しています9
StringBuilder str
= new StringBuilder("a");
str.append("b");
str.append("c");
1003
“a”
1000
1001
1002
1003
1004
1005
1006
アドレス メモリ
str
辛い現実
1005
“a”
“ab”
“b”
メモリ
str
連結するたびに新しいオブジェクトを生成
1002
“abc”
“a”
“c”
“ab”
“b”
メモリ
str 1002
“a”
“a”
1000
1001
1002
1003
1004
1005
1006
アドレス メモリ
str
ちょっとましな現実
1002
“ab”
“a”
“b”
メモリ
str
同じオブジェクトに文字列が連結される
1002
“abc”
“a”
“c”
“b”
メモリ
str
- 11. 鉄則2 文字列比較にはequals()メソッドを使う
だめな例:文字列を==で比較
String str1 = "123";
if (str1 == "123") {
System.out.println("だめな例: true");
} else {
System.out.println("だめな例: false");
}
String str2 = "123";
if ("123".equals(str2)) {
System.out.println("よい例: true");
} else {
System.out.println("よい例: false");
}
よい例:文字列をequalsメソッドで比較
11
- 17. 鉄則3 整数型の取りうる値の範囲を把握する
ビックリする例
int num1 = 2147483647;
System.out.println(num1);
System.out.println(num1 + 1);
int型の数直線イメージ 辛い現実
最大値
最小値
2147483647
0
-2147483648
最大値
最小値
-1
2147483647
-2147483648
0
17
いずれにせよ、最大値を超えると最小値に、最小値を下回ると最大値になる
- 19. 鉄則4 浮動小数点数のしくみをだいたい理解する
おかしな例
double num1 = 1.7976931348623155;
System.out.println(num1);
System.out.println(num1 + 0.0000000000000001); // 最後の桁に1を足す
符号 指数 仮数
正負 小数点の位置 実際の数値の整数表現
この例では…
+ 17桁目 17976931348623155
(最大の桁数を超えている部分は計算できない!)
float型、double型は内部で3つの部分に分かれている
実際は指数部は2進数の桁数ですが、分かりやすくするために10進数として説明しています
実数型の選択方針:精度の問題を回避するため、
制約がなければ常にdouble型を使う
19
- 21. 鉄則5 プリミティブ型と参照型の違いを理解する
プリミティブ型を引数としたメソッド呼び出しの例
int var1 = 1;
obj.execute(var1);
System.out.println(var1);
public void execute(int par1) {
par1++;
}
int[] var2 = {1};
obj.execute(var2);
System.out.println(var2[0]);
public void execute(int[] par2) {
par2[0]++;
}
参照型を引数としたメソッド呼び出しの例
21
- 23. 鉄則6 ボクシング・アンボクシングは最少にする
だめな例
public void execute(List<Integer> integerList) {
Integer val1 = integerList.get(0);
val1++;
System.out.println(val1);
}
public void execute(List<Integer> integerList) {
int val2 = integerList.get(0);
val2++;
System.out.println(val2);
}
よい例
23
- 26. 鉄則7 正しいコレクションの型を利用する
だめな例:HashMapの値に常にnullを挿入
Map<Profile, Object> profileHashMap
= new HashMap<Profile, Object>();
private void execute(Profile profile) {
profileHashMap.put(profile, null);
}
Set<Profile> profileHashSet = new HashSet<Profile>();
private void execute(Profile profile) {
profileHashSet.add(profile);
}
よい例:HashSetを使用
26
- 27. 鉄則7 正しいコレクションの型を利用する
だめな例:要素が重複しないようにArrayListに挿入
List<Profile> profileArrayList = new ArrayList<Profile>();
private void execute(Profile profile) {
if (!profileArrayList.contains(profile)) {
profileArrayList.add(profile);
}
}
Set<Profile> profileLinkedHashSet
= new LinkedHashSet<Profile>();
private void execute(Profile profile) {
profileLinkedHashSet.add(profile);
}
よい例:LinkedHashSetを使用
27
- 29. 鉄則7 正しいコレクションの型を利用する
正しいコレクションを選択する
List Set Map
順序が不要 - HashSet HashMap
順序が必要
ArrayList
LinkedList
LinkedHashSet LinkedHashMap
ソートが必要 - TreeSet TreeMap
ArrayListとLinkedListの選択方針
読込(ランダムアクセス)が中心 ArrayList
挿入や削除が多い LinkedList
書換えが多い ArrayList
29
※これらのクラスはすべて
スレッドアンセーフである
- 33. 鉄則9 ストリームにはバッファを利用する
だめな例:1バイトずつ読み書きする
OutputStream output1 = null;
output1 = new FileOutputStream("output/output1.txt");
output1.write(text.getBytes());
InputStream input1 = null;
input1 = new FileInputStream("output/output1.txt");
byte[] buf = new byte[4096];
int len;
while ((len = input1.read(buf)) != -1) {
System.out.write(buf, 0, len);
}
33
- 34. 鉄則9 ストリームにはバッファを利用する
よい例:バッファを利用して数バイトずつ読み書きする
BufferedOutputStream output2 = null;
output2 = new BufferedOutputStream(
new FileOutputStream("output/output2.txt"));
output2.write(text.getBytes());
output2.flush();
BufferedInputStream input2 = null;
input2 = new BufferedInputStream(
new FileInputStream("output/output2.txt"));
byte[] buf = new byte[4096];
int len;
while ((len = input2.read(buf)) != -1) {
System.out.write(buf, 0, len);
}
34
- 35. 鉄則9 ストリームにはバッファを利用する
だめな例:1文字ずつ読み書きする
Writer output3 = null;
output3 = new FileWriter("output/output3.txt");
output3.write(text);
Reader input3 = null;
input3 = new FileReader("output/output3.txt");
char[] cbuf = new char[4096];
int len;
while ((len = input3.read(cbuf)) != -1) {
System.out.write(String.valueOf(cbuf).getBytes(), 0, len);
}
35
- 36. 鉄則9 ストリームにはバッファを利用する
よい例:バッファを利用して数文字ずつ読み書きする
BufferedWriter output4 = null;
output4 = new BufferedWriter(
new FileWriter("output/output4.txt"));
output4.write(text);
output4.flush();
BufferedReader input4 = null;
input4 = new BufferedReader(
new FileReader("output/example/output4.txt"));
String line;
while ((line = input4.readLine()) != null) {
System.out.println(line);
}
36
- 37. 鉄則9 ストリームにはバッファを利用する
1バイト・1文字ずつ読み書きする基本ストリームクラス
読み込み 書き込み
バイトストリーム InputStream OutputStream
文字ストリーム Reader Writer
バッファに溜めてから読み書きするラッパストリームクラス
読み込み 書き込み
バイトストリーム BufferedInputStream BufferedOutputStream
文字ストリーム BufferedReader BufferedWriter
ディスクアクセスが頻繁に起こるため低速
一旦バッファに溜めることでディスクアクセスの頻度を減らす
37
- 39. 鉄則10 ストリームは必ずclose()する
だめな例:ストリームをクローズしない
BufferedWriter output = null;
try {
output = new BufferedWriter(
new FileWriter("output/output4.txt"));
output.write(text);
output.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
39
- 40. 鉄則10 ストリームは必ずclose()する
よい例:ストリームをクローズする
BufferedWriter output = null;
try {
output = new BufferedWriter(
new FileWriter("output/output4.txt"));
output.write(text);
output.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} 40
- 41. 鉄則10 ストリームは必ずclose()する
よい例:Java 7のtry-with-resources文を用いる
try (BufferedWriter output = new BufferedWriter(new FileWriter(
"output/output4.txt"))) {
output3.write(text);
output3.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
41
- 43. 鉄則11 例外を具体的な型でキャッチし処理する
だめな例1:例外をどこでもキャッチしない
public void execute(String path) throws Exception {
BufferedReader input = new BufferedReader(
new FileReader(path));
String line;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
if (input != null) {
input.close();
}
}
43
- 45. 鉄則11 例外を具体的な型でキャッチし処理する
よい例:例外を具体的な型でキャッチし適切に処理する
public void execute(String path) {
try (BufferedReader input = new BufferedReader(
new FileReader(path))) {
String line;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.err.println("execute1メソッドで例外が発生:"
+ path + "が見つかりません");
} catch (IOException e) {
e.printStackTrace();
System.err.println("execute1メソッドで例外が発生:"
+ path + "の読み込みに失敗しました");
}
}
45
- 62. まとめ リファクタリングショートカットキー
62
コマンド Mac Windows
メソッドの抽出 ⌘+Option+M Alt+Shift+M
インライン化 ⌘+Option+I Alt+Shift+I
ローカル変数の抽出 ⌘+Option+L Alt+Shift+L
名前変更 ⌘+Option+R Alt+Shift+R
定数の抽出 なし なし
メソッドシグニチャの変更 ⌘+Option+C Alt+Shift+C
移動 ⌘+Option+V Alt+Shift+V
要素コメントの生成 ⌘+Option+J Alt+Shift+J
- 65. 参考文献
65
パーフェクトJava 技術評論社 アリエル・ネットワーク株式会社
(著), 井上 誠一郎 (著), 永井 雅人 (著), 松山 智大 (著)
Sun SJC-P認定ガイド 日経BP社 Kathy Sierra (著), Bert Bates (著),
トップスタジオ (著)
WEB+DB PRESS Vol.37 技術評論社
WEB+DB PRESS Vol.52 技術評論社
内容に関するご指摘等は@inatusまでお願いいたします