首先先設計個像Map的泛型:
class Chess<K, V> { private K key; private V value; public Chess(K key, V value) { this.setKey(key); this.setValue(value); } public K getKey() { return key; } public void setKey(K key) { this.key = key; } public V getValue() { return value; } public void setValue(V value) { this.value = value; } }
然後再設計個像List的泛型
class Msg<T> { private T info; public Msg(T m) { this.setInfo(m); } public T getInfo() { return info; } public void setInfo(T info) { this.info = info; } }
寫個測試類:
Chess<String, Integer> chess = new Chess<>("象棋", 32); Msg<Chess<String, Integer>> msg = new Msg<>(chess); System.out.print(msg.getInfo().getKey() + "有"); System.out.println(msg.getInfo().getValue() + "顆棋子!");
結果: 象棋有32顆棋子!
沒有留言:
張貼留言