Last active
May 14, 2018 02:03
-
-
Save xujiaji/02bdfdcef389e6ecf3a39b3c364a91d2 to your computer and use it in GitHub Desktop.
Java编程思想:17.4【用适配器仿真潜在类型机制】,填充
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public interface Addable<T> { void add(T t); } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Fill | |
| { | |
| public static <T> void fill(Collection<T> collection, Class<? extends T> classToken, int size) | |
| { | |
| for (int i = 0; i < size; i++) | |
| { | |
| try | |
| { | |
| collection.add(classToken.newInstance()); | |
| } catch (Exception e) | |
| { | |
| throw new RuntimeException(e); | |
| } | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Fill2 | |
| { | |
| public static <T> void fill(Addable<T> addable, Class<? extends T> classToken, int size) | |
| { | |
| for (int i = 0; i < size; i++) | |
| { | |
| try | |
| { | |
| addable.add(classToken.newInstance()); | |
| } catch (Exception e) | |
| { | |
| throw new RuntimeException(e); | |
| } | |
| } | |
| } | |
| public static <T> void fill(Addable<T> addable, Generator<T> generator, int size) | |
| { | |
| for (int i = 0; i < size; i++) | |
| { | |
| addable.add(generator.next()); | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fill2 的使用
Fill2对Collection的要求与Fill不同,它只需要实现Addable的对象,它是帮帮助我们创建潜在类型的一种体现。