SlideShare a Scribd company logo
1 of 37
ジェネリックプログラミング入門
Java編
2018/12/7
第2事業部 市岡 岳彦
© 2018 SG Corporation 2
1. 動機
2. ジェネリックメソッド
3. ジェネリック型
4. ジェネリッククラス
5. 再帰型境界
6. まとめ
目次
© 2018 SG Corporation 3
◍ Collectionの末尾に指定された要素を追加する。
◍ String
◍ Integer
1. 動機
static void fill(Collection<String> c, String e, int size) {
for (int i = c.size(); i < size; i++) {
c.add(e);
}
}
static void fill(Collection<Integer> c, Integer e, int size) {
for (int i = c.size(); i < size; i++) {
c.add(e);
}
}
© 2018 SG Corporation 4
◍ Collectionの末尾に指定された要素を追加する。
◍ Objectでやる。
◍ 問題:どんな型でも受け付けてしまう。
1. 動機
static void fill(Collection<Object> c, Object e, int size) {
for (int i = c.size(); i < size; i++) {
c.add(e);
}
}
© 2018 SG Corporation 5
◍ Collectionの末尾に指定された要素を追加する。
◍ 型をパラメータ化して、呼ぶ方で型を決めればいい。
1. 動機
class MethodSample {
…
static <E> void fill(Collection<E> c, E e, int size) {
for (int i = c.size(); i < size; i++) {
c.add(e);
}
}
MethodSample.<String>fill(strList, "banana", 10);
MethodSample.<Integer>fill(intList, 123, 10);
© 2018 SG Corporation 6
◍ メソッド呼び出し時に、パラメータに実際の値をバインドするのに似ている。
◍ 実行時ではなく、コンパイル時に型パラメータに実際の型をバインドする。
◍ 型を特定しない汎用的なアルゴリズムと静的型付けの安全性を両立。
1. 動機
© 2018 SG Corporation 7
◍ 型のパラメータ化
◍ メソッド定義時
◍ 実際の型のバインド
◍ メソッド呼び出し時
◍ 型推論
2. ジェネリックメソッド
static <E> void fill(Collection<E> c, E e, int size) {
…
}
MethodSample.<String>fill(strList, "banana", 10);
List<String> strList = new ArrayList<>();
MethodSample.fill(strList, "banana", 10);
© 2018 SG Corporation 8
◍ ジェネリック型変数の継承関係について
◍ スーパータイプの変数にはサブタイプの変数を代入可能
◍ 配列でも同じ
3. ジェネリック型
Object obj = …
String str = …
obj = str;
Object[] objArray = …
String[] strArray = …
objArray = strArray;
© 2018 SG Corporation 9
◍ List<String>はList<Object>のサブタイプではない。
◍ 代入不可能
◍ もし、代入可能だとしたら…
3. ジェネリック型
List<Object> objList = …
List<String> strList = …
objList = strList; // コンパイルエラー!
objList = strList;
objList.add(123);
// objListの実体はList<String>
// List<String>にIntegerを入れられてしまう。
© 2018 SG Corporation 10
◍ 動機
◍ ジェネリック型変数で継承関係を表現したい。
◍ 境界ワイルドカード型を使う。
3. ジェネリック型
© 2018 SG Corporation 11
◍ 境界ワイルドカード型
◍ 下限ワイルドカード:IN方向のみ可能
◍ 上限ワイルドカード:OUT方向のみ可能
3. ジェネリック型
List<String> strList = …
List<? super String> superStrList = strList;
superStrList.add("orange");
String str = superStrList.get(0); // コンパイルエラー!
List<String> strList = …
List<? extends String> subStrList = strList;
String str = subStrList.get(0);
subStrList.add("grape"); // コンパイルエラー!
© 2018 SG Corporation 12
◍ 下限ワイルドカード:IN方向のみ可能
◍ Stringのスーパータイプであれば、許容するList。
◍ IN方向はStringのスーパータイプであれば、適用可能。
◍ OUT方向はStringである保証ができないため、コンパイルエラーとなる。
3. ジェネリック型
List<String> strList = …
List<? super String> superStrList = strList;
superStrList.add("orange");
String str = superStrList.get(0); // コンパイルエラー!
© 2018 SG Corporation 13
◍ 下限ワイルドカード境界型パラメータの例
◍ Collectionの末尾に指定された要素を追加する。
3. ジェネリック型
static <E> void fill(Collection<? super E> c, E e, int size) {
for (int i = c.size(); i < size; i++) {
c.add(e);
}
}
…
List<Object> l = new ArrayList<>();
fill(l, "banana", 10);
© 2018 SG Corporation 14
◍ 上限ワイルドカード:OUT方向のみ可能
◍ Stringのサブタイプであれば、許容するList。
◍ OUT方向はStringのサブタイプであれば、適用可能。
◍ IN方向は任意のサブタイプである保証ができないため、コンパイルエラーとな
る。
3. ジェネリック型
List<String> strList = …
List<? extends String> subStrList = strList;
String str = subStrList.get(0);
subStrList.add("grape"); // コンパイルエラー!
© 2018 SG Corporation 15
◍ 上限ワイルドカード境界型パラメータの例
◍ Collectionを連結する。
3. ジェネリック型
static <E> void concat(Collection<? super E> dst,
Collection<? extends E> src) {
for (E e : src) {
dst.add(e);
}
}
…
List<Number> ln = …
List<Integer> li = …
concat(ln, li);
© 2018 SG Corporation 16
◍ 上限ワイルドカード境界型パラメータの例
◍ Listを逆転する。
◍ 戻り値を境界ワイルドカードにすると、メソッド使用者の負担になる。
3. ジェネリック型
static <E> List<? super E> reverse(List<? extends E> l) {
List<E> rev = new ArrayList<>(l.size());
for (int i = l.size() - 1; i >= 0; i--) {
rev.add(l.get(i));
}
return rev;
}
List<? super String> s = reverse(l);
List<Object> o = reverse(l); // コンパイルエラー!
© 2018 SG Corporation 17
◍ 動機
◍ ジェネリック型のスーパータイプが欲しい
◍ 非境界ワイルドカード型を使う。
3. ジェネリック型
© 2018 SG Corporation 18
◍ 非境界ワイルドカード型の例
◍ <Object>とも違い、何型でもないので、null以外代入できない。
◍ 取得側は必ずObjectに代入する。
◍ 型安全性は保証される。
3. ジェネリック型
List<String> strList = …
List<?> unknownList = strList;
Object obj = unknownList.get(0);
unknownList.add(null);
unknownList.add("apple"); // コンパイルエラー!
© 2018 SG Corporation 19
◍ 非境界ワイルドカード型は何に使うのか。
◍ Listをローテーションする。
3. ジェネリック型
static void rotate(List<?> l, int size) {
rotateHelper(l, size);
}
private static <E> void rotateHelper(List<E> l, int size) {
size %= l.size();
for (int i = 0; i < size; i++) {
l.add(l.get(0));
l.remove(0);
}
}
© 2018 SG Corporation 20
◍ 非境界ワイルドカード型は何に使うのか。
の方が
よりも
APIを使う側にとって、より簡潔。
…と、Effective Javaに書いてあったが、よくわからない。そうなのか?
3. ジェネリック型
static void rotate(List<?> l, int size)
static <E> void rotate(List<E> l, int size)
© 2018 SG Corporation 21
◍ 当たり前のようにCollection<E>とか使ってたけど。
◍ ところで、ジェネリック型のクラスをどのように作るのか?
4. ジェネリッククラス
© 2018 SG Corporation 22
◍ 範囲を表すクラスを考えてみる。
◍ 開始と終了をフィールドとして持つ。
◍ 開始と終了は同じ型。
◍ 開始と終了はComparableのサブタイプであれば、なんでもいい。
4. ジェネリッククラス
© 2018 SG Corporation 23
◍ 範囲を表すクラスを考えてみる。
4. ジェネリッククラス
class Range<E extends Comparable<E>> {
private E begin;
private E end;
Range(E begin, E end) {
this.begin = begin;
this.end = end;
}
…
}
© 2018 SG Corporation 24
◍ 型のパラメータ化
◍ クラス定義時
◍ 実際の型のバインド
◍ 変数宣言時
◍ 継承時
4. ジェネリッククラス
class Range<E extends Comparable<E>> {
…
}
Range<Integer> range = new Range<>(1, 10);
class LongRange extends Range<Long> {
LongRange(Long begin, Long end) {
super(begin, end);
…
© 2018 SG Corporation 25
◍ 型パラメータの範囲を限定する。
◍ Comparableのサブタイプのみバインド可能
4. ジェネリッククラス
class Range<E extends Comparable<E>> {
…
Range<Number> numberRange = …
// コンパイルエラー!
© 2018 SG Corporation 26
◍ 範囲といえば、日付型。
◍ java.time.LocalDateはComparable<LocalDate>型ではなく、
Comparable<ChronoLocalDate>型。
4. ジェネリッククラス
Range<LocalDate> dateRange = new Range<>(LocalDate.of(2018, 1, 1),
LocalDate.of(2018, 3, 31));
// コンパイルエラー!
ChronoLocalDate implements Comparable<ChronoLocalDate>
LocalDate implements ChronoLocalDate
© 2018 SG Corporation 27
◍ Comparableにバインドする型を下限境界にする。
4. ジェネリッククラス
class Range<E extends Comparable<? super E>> {
private E begin;
private E end;
Range(E begin, E end) {
this.begin = begin;
this.end = end;
}
…
}
Range<LocalDate> dateRange = new Range<>(LocalDate.of(2018, 1, 1),
LocalDate.of(2018, 3, 31));
// OK!
© 2018 SG Corporation 28
◍ 継承時の型バインドは多段継承と相性が悪い。
4. ジェネリッククラス
© 2018 SG Corporation 29
◍ java.lang.Enum<E>
◍ これは何か。
◍ 型パラメータが宣言しているタイプのサブタイプであることを強制する。
→Enum<Foo>のFooは必ずEnumのサブタイプである。
◍ スーパークラスの型ではなく、個々の型で変数宣言することを前提とする。
◍ 一般的にインターフェース、抽象クラスで使う。
5. 再帰型境界
Enum<E extends Enum<E>>
Enum<Foo> foo = … // という使い方はしない。
Foo foo = … // として使う。
© 2018 SG Corporation 30
◍ 動機
◍ ジェネリッククラスのメソッドの引数の型を特定の型に限定したい。
◍ 範囲型再登場
◍ 範囲が重複しているかをチェックするメソッドを追加。
5. 再帰型境界
abstract class Range<E extends Comparable<? super E>> {
protected E begin;
protected E end;
boolean overlap(Range<E> t) {
return begin.compareTo(t.end) <= 0 &&
t.begin.compareTo(end) <= 0;
}
…
© 2018 SG Corporation 31
◍ 範囲が重複しているか。
◍ 比較相手はRange<E>のサブタイプではあるが、自分と同じ型とは限らない。
5. 再帰型境界
abstract class Range<E extends Comparable<? super E>> {
protected E begin;
protected E end;
boolean overlap(Range<E> t) {
return begin.compareTo(t.end) <= 0 &&
t.begin.compareTo(end) <= 0;
}
…
class LongRange extends Range<Long>
class AnotherLongRange extends Range<Long>
© 2018 SG Corporation 32
◍ 範囲が重複しているか。
5. 再帰型境界
abstract class Range<E extends Comparable<? super E>,
T extends Range<E,T>> {
protected E begin;
protected E end;
boolean overlap(T t) {
return begin.compareTo(t.end) <= 0 &&
t.begin.compareTo(end) <= 0;
}
…
class LongRange extends Range<Long, LongRange>
class AnotherLongRange extends Range<Long, AnotherLongRange>
© 2018 SG Corporation 33
◍ 範囲が重複しているか。
◍ 具体的な型をサブタイプ実装時まで保留できる。
◍ 比較する相手が自分と同じ型であることを保証する。
5. 再帰型境界
abstract class Range<E extends Comparable<? super E>,
T extends Range<E,T>> {
protected E begin;
protected E end;
boolean overlap(T t) {
return begin.compareTo(t.end) <= 0 &&
t.begin.compareTo(end) <= 0;
}
…
© 2018 SG Corporation 34
◍ 型のパラメータ化とバインドのタイミングを理解しよう。
◍ 境界ワイルドカード型で役割を表現しよう。
◍ 戻り値は境界ワイルドカードにしない。
◍ 非境界ワイルドカード型のメソッドはヘルパーメソッドを作ろう。
◍ 継承時の型バインドは多段継承と相性が悪い。
◍ 型パラメータがサブタイプであって欲しい時は再起型境界を使おう。
6. まとめ
© 2018 SG Corporation 35
◍ Effective Java 第2版
 Joshua Bloch 著
 柴田 芳樹 訳
 丸善出版
参考文献
© 2018 SG Corporation 36
◍ https://blog.sgnet.co.jp
◍ https://www.slideshare.net/t_ichioka_sg/
こちらもどうぞ
© 2017 SG Corporation 37
顧客と社員に信頼されるエス・ジー

More Related Content

Featured

Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Applitools
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at WorkGetSmarter
 

Featured (20)

Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
Unlocking the Power of ChatGPT and AI in Testing - A Real-World Look, present...
 
12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work12 Ways to Increase Your Influence at Work
12 Ways to Increase Your Influence at Work
 

ジェネリックプログラミング入門

  • 2. © 2018 SG Corporation 2 1. 動機 2. ジェネリックメソッド 3. ジェネリック型 4. ジェネリッククラス 5. 再帰型境界 6. まとめ 目次
  • 3. © 2018 SG Corporation 3 ◍ Collectionの末尾に指定された要素を追加する。 ◍ String ◍ Integer 1. 動機 static void fill(Collection<String> c, String e, int size) { for (int i = c.size(); i < size; i++) { c.add(e); } } static void fill(Collection<Integer> c, Integer e, int size) { for (int i = c.size(); i < size; i++) { c.add(e); } }
  • 4. © 2018 SG Corporation 4 ◍ Collectionの末尾に指定された要素を追加する。 ◍ Objectでやる。 ◍ 問題:どんな型でも受け付けてしまう。 1. 動機 static void fill(Collection<Object> c, Object e, int size) { for (int i = c.size(); i < size; i++) { c.add(e); } }
  • 5. © 2018 SG Corporation 5 ◍ Collectionの末尾に指定された要素を追加する。 ◍ 型をパラメータ化して、呼ぶ方で型を決めればいい。 1. 動機 class MethodSample { … static <E> void fill(Collection<E> c, E e, int size) { for (int i = c.size(); i < size; i++) { c.add(e); } } MethodSample.<String>fill(strList, "banana", 10); MethodSample.<Integer>fill(intList, 123, 10);
  • 6. © 2018 SG Corporation 6 ◍ メソッド呼び出し時に、パラメータに実際の値をバインドするのに似ている。 ◍ 実行時ではなく、コンパイル時に型パラメータに実際の型をバインドする。 ◍ 型を特定しない汎用的なアルゴリズムと静的型付けの安全性を両立。 1. 動機
  • 7. © 2018 SG Corporation 7 ◍ 型のパラメータ化 ◍ メソッド定義時 ◍ 実際の型のバインド ◍ メソッド呼び出し時 ◍ 型推論 2. ジェネリックメソッド static <E> void fill(Collection<E> c, E e, int size) { … } MethodSample.<String>fill(strList, "banana", 10); List<String> strList = new ArrayList<>(); MethodSample.fill(strList, "banana", 10);
  • 8. © 2018 SG Corporation 8 ◍ ジェネリック型変数の継承関係について ◍ スーパータイプの変数にはサブタイプの変数を代入可能 ◍ 配列でも同じ 3. ジェネリック型 Object obj = … String str = … obj = str; Object[] objArray = … String[] strArray = … objArray = strArray;
  • 9. © 2018 SG Corporation 9 ◍ List<String>はList<Object>のサブタイプではない。 ◍ 代入不可能 ◍ もし、代入可能だとしたら… 3. ジェネリック型 List<Object> objList = … List<String> strList = … objList = strList; // コンパイルエラー! objList = strList; objList.add(123); // objListの実体はList<String> // List<String>にIntegerを入れられてしまう。
  • 10. © 2018 SG Corporation 10 ◍ 動機 ◍ ジェネリック型変数で継承関係を表現したい。 ◍ 境界ワイルドカード型を使う。 3. ジェネリック型
  • 11. © 2018 SG Corporation 11 ◍ 境界ワイルドカード型 ◍ 下限ワイルドカード:IN方向のみ可能 ◍ 上限ワイルドカード:OUT方向のみ可能 3. ジェネリック型 List<String> strList = … List<? super String> superStrList = strList; superStrList.add("orange"); String str = superStrList.get(0); // コンパイルエラー! List<String> strList = … List<? extends String> subStrList = strList; String str = subStrList.get(0); subStrList.add("grape"); // コンパイルエラー!
  • 12. © 2018 SG Corporation 12 ◍ 下限ワイルドカード:IN方向のみ可能 ◍ Stringのスーパータイプであれば、許容するList。 ◍ IN方向はStringのスーパータイプであれば、適用可能。 ◍ OUT方向はStringである保証ができないため、コンパイルエラーとなる。 3. ジェネリック型 List<String> strList = … List<? super String> superStrList = strList; superStrList.add("orange"); String str = superStrList.get(0); // コンパイルエラー!
  • 13. © 2018 SG Corporation 13 ◍ 下限ワイルドカード境界型パラメータの例 ◍ Collectionの末尾に指定された要素を追加する。 3. ジェネリック型 static <E> void fill(Collection<? super E> c, E e, int size) { for (int i = c.size(); i < size; i++) { c.add(e); } } … List<Object> l = new ArrayList<>(); fill(l, "banana", 10);
  • 14. © 2018 SG Corporation 14 ◍ 上限ワイルドカード:OUT方向のみ可能 ◍ Stringのサブタイプであれば、許容するList。 ◍ OUT方向はStringのサブタイプであれば、適用可能。 ◍ IN方向は任意のサブタイプである保証ができないため、コンパイルエラーとな る。 3. ジェネリック型 List<String> strList = … List<? extends String> subStrList = strList; String str = subStrList.get(0); subStrList.add("grape"); // コンパイルエラー!
  • 15. © 2018 SG Corporation 15 ◍ 上限ワイルドカード境界型パラメータの例 ◍ Collectionを連結する。 3. ジェネリック型 static <E> void concat(Collection<? super E> dst, Collection<? extends E> src) { for (E e : src) { dst.add(e); } } … List<Number> ln = … List<Integer> li = … concat(ln, li);
  • 16. © 2018 SG Corporation 16 ◍ 上限ワイルドカード境界型パラメータの例 ◍ Listを逆転する。 ◍ 戻り値を境界ワイルドカードにすると、メソッド使用者の負担になる。 3. ジェネリック型 static <E> List<? super E> reverse(List<? extends E> l) { List<E> rev = new ArrayList<>(l.size()); for (int i = l.size() - 1; i >= 0; i--) { rev.add(l.get(i)); } return rev; } List<? super String> s = reverse(l); List<Object> o = reverse(l); // コンパイルエラー!
  • 17. © 2018 SG Corporation 17 ◍ 動機 ◍ ジェネリック型のスーパータイプが欲しい ◍ 非境界ワイルドカード型を使う。 3. ジェネリック型
  • 18. © 2018 SG Corporation 18 ◍ 非境界ワイルドカード型の例 ◍ <Object>とも違い、何型でもないので、null以外代入できない。 ◍ 取得側は必ずObjectに代入する。 ◍ 型安全性は保証される。 3. ジェネリック型 List<String> strList = … List<?> unknownList = strList; Object obj = unknownList.get(0); unknownList.add(null); unknownList.add("apple"); // コンパイルエラー!
  • 19. © 2018 SG Corporation 19 ◍ 非境界ワイルドカード型は何に使うのか。 ◍ Listをローテーションする。 3. ジェネリック型 static void rotate(List<?> l, int size) { rotateHelper(l, size); } private static <E> void rotateHelper(List<E> l, int size) { size %= l.size(); for (int i = 0; i < size; i++) { l.add(l.get(0)); l.remove(0); } }
  • 20. © 2018 SG Corporation 20 ◍ 非境界ワイルドカード型は何に使うのか。 の方が よりも APIを使う側にとって、より簡潔。 …と、Effective Javaに書いてあったが、よくわからない。そうなのか? 3. ジェネリック型 static void rotate(List<?> l, int size) static <E> void rotate(List<E> l, int size)
  • 21. © 2018 SG Corporation 21 ◍ 当たり前のようにCollection<E>とか使ってたけど。 ◍ ところで、ジェネリック型のクラスをどのように作るのか? 4. ジェネリッククラス
  • 22. © 2018 SG Corporation 22 ◍ 範囲を表すクラスを考えてみる。 ◍ 開始と終了をフィールドとして持つ。 ◍ 開始と終了は同じ型。 ◍ 開始と終了はComparableのサブタイプであれば、なんでもいい。 4. ジェネリッククラス
  • 23. © 2018 SG Corporation 23 ◍ 範囲を表すクラスを考えてみる。 4. ジェネリッククラス class Range<E extends Comparable<E>> { private E begin; private E end; Range(E begin, E end) { this.begin = begin; this.end = end; } … }
  • 24. © 2018 SG Corporation 24 ◍ 型のパラメータ化 ◍ クラス定義時 ◍ 実際の型のバインド ◍ 変数宣言時 ◍ 継承時 4. ジェネリッククラス class Range<E extends Comparable<E>> { … } Range<Integer> range = new Range<>(1, 10); class LongRange extends Range<Long> { LongRange(Long begin, Long end) { super(begin, end); …
  • 25. © 2018 SG Corporation 25 ◍ 型パラメータの範囲を限定する。 ◍ Comparableのサブタイプのみバインド可能 4. ジェネリッククラス class Range<E extends Comparable<E>> { … Range<Number> numberRange = … // コンパイルエラー!
  • 26. © 2018 SG Corporation 26 ◍ 範囲といえば、日付型。 ◍ java.time.LocalDateはComparable<LocalDate>型ではなく、 Comparable<ChronoLocalDate>型。 4. ジェネリッククラス Range<LocalDate> dateRange = new Range<>(LocalDate.of(2018, 1, 1), LocalDate.of(2018, 3, 31)); // コンパイルエラー! ChronoLocalDate implements Comparable<ChronoLocalDate> LocalDate implements ChronoLocalDate
  • 27. © 2018 SG Corporation 27 ◍ Comparableにバインドする型を下限境界にする。 4. ジェネリッククラス class Range<E extends Comparable<? super E>> { private E begin; private E end; Range(E begin, E end) { this.begin = begin; this.end = end; } … } Range<LocalDate> dateRange = new Range<>(LocalDate.of(2018, 1, 1), LocalDate.of(2018, 3, 31)); // OK!
  • 28. © 2018 SG Corporation 28 ◍ 継承時の型バインドは多段継承と相性が悪い。 4. ジェネリッククラス
  • 29. © 2018 SG Corporation 29 ◍ java.lang.Enum<E> ◍ これは何か。 ◍ 型パラメータが宣言しているタイプのサブタイプであることを強制する。 →Enum<Foo>のFooは必ずEnumのサブタイプである。 ◍ スーパークラスの型ではなく、個々の型で変数宣言することを前提とする。 ◍ 一般的にインターフェース、抽象クラスで使う。 5. 再帰型境界 Enum<E extends Enum<E>> Enum<Foo> foo = … // という使い方はしない。 Foo foo = … // として使う。
  • 30. © 2018 SG Corporation 30 ◍ 動機 ◍ ジェネリッククラスのメソッドの引数の型を特定の型に限定したい。 ◍ 範囲型再登場 ◍ 範囲が重複しているかをチェックするメソッドを追加。 5. 再帰型境界 abstract class Range<E extends Comparable<? super E>> { protected E begin; protected E end; boolean overlap(Range<E> t) { return begin.compareTo(t.end) <= 0 && t.begin.compareTo(end) <= 0; } …
  • 31. © 2018 SG Corporation 31 ◍ 範囲が重複しているか。 ◍ 比較相手はRange<E>のサブタイプではあるが、自分と同じ型とは限らない。 5. 再帰型境界 abstract class Range<E extends Comparable<? super E>> { protected E begin; protected E end; boolean overlap(Range<E> t) { return begin.compareTo(t.end) <= 0 && t.begin.compareTo(end) <= 0; } … class LongRange extends Range<Long> class AnotherLongRange extends Range<Long>
  • 32. © 2018 SG Corporation 32 ◍ 範囲が重複しているか。 5. 再帰型境界 abstract class Range<E extends Comparable<? super E>, T extends Range<E,T>> { protected E begin; protected E end; boolean overlap(T t) { return begin.compareTo(t.end) <= 0 && t.begin.compareTo(end) <= 0; } … class LongRange extends Range<Long, LongRange> class AnotherLongRange extends Range<Long, AnotherLongRange>
  • 33. © 2018 SG Corporation 33 ◍ 範囲が重複しているか。 ◍ 具体的な型をサブタイプ実装時まで保留できる。 ◍ 比較する相手が自分と同じ型であることを保証する。 5. 再帰型境界 abstract class Range<E extends Comparable<? super E>, T extends Range<E,T>> { protected E begin; protected E end; boolean overlap(T t) { return begin.compareTo(t.end) <= 0 && t.begin.compareTo(end) <= 0; } …
  • 34. © 2018 SG Corporation 34 ◍ 型のパラメータ化とバインドのタイミングを理解しよう。 ◍ 境界ワイルドカード型で役割を表現しよう。 ◍ 戻り値は境界ワイルドカードにしない。 ◍ 非境界ワイルドカード型のメソッドはヘルパーメソッドを作ろう。 ◍ 継承時の型バインドは多段継承と相性が悪い。 ◍ 型パラメータがサブタイプであって欲しい時は再起型境界を使おう。 6. まとめ
  • 35. © 2018 SG Corporation 35 ◍ Effective Java 第2版  Joshua Bloch 著  柴田 芳樹 訳  丸善出版 参考文献
  • 36. © 2018 SG Corporation 36 ◍ https://blog.sgnet.co.jp ◍ https://www.slideshare.net/t_ichioka_sg/ こちらもどうぞ
  • 37. © 2017 SG Corporation 37 顧客と社員に信頼されるエス・ジー