This shows you the differences between two versions of the page.
— |
java:generics_multiple_params [2017/02/17 15:02] (current) gthanos created |
||
---|---|---|---|
Line 1: | Line 1: | ||
+ | ====== Παραμετρικοί τύποι δεδομένων με πολλές παραμέτρους ====== | ||
+ | Δείτε το παρακάτω παράδειγμα, όπου έχουμε ένα interface και μία κλάση με δύο παραμέτρους. | ||
+ | |||
+ | <code java Pair.java> | ||
+ | public interface Pair<K, V> { | ||
+ | public K getKey(); | ||
+ | public V getValue(); | ||
+ | public void setKey(K key); | ||
+ | public void setValue(V value); | ||
+ | } | ||
+ | </code> | ||
+ | |||
+ | <code java OrderedPair.java> | ||
+ | public class OrderedPair<K, V> implements Pair<K,V> { | ||
+ | |||
+ | private K key; | ||
+ | private V value; | ||
+ | |||
+ | public OrderedPair(K key, V value) { | ||
+ | this.key = key; | ||
+ | this.value = value; | ||
+ | } | ||
+ | |||
+ | public void setKey(K key) { this.key = key; } | ||
+ | public void setValue(V value) { this.value = value; } | ||
+ | public K getKey() { return key; } | ||
+ | public V getValue() { return value; } | ||
+ | } | ||
+ | </code> | ||
+ | |||
+ | Με βάση τον παραπάνω κώδικα μπορείτε να δημιουργήσετε αντικείμενα επιμέρους τύπων ως εξής: | ||
+ | <code java OrderedPairUsage.java> | ||
+ | public class OrderedPairUsage { | ||
+ | public static void main(String args[]) { | ||
+ | Pair<String, Integer> p1 = new OrderedPair<String, Integer>("Even", 8); | ||
+ | Pair<String, String> p2 = new OrderedPair<String, String>("hello", "world"); | ||
+ | OrderedPair<String, Box<Integer>> p = new OrderedPair<>("primes", new Box<Integer>()); | ||
+ | // the following is not allowed | ||
+ | Pair<String, Integer> p1 = new OrderedPair<>("hello", "world"); | ||
+ | } | ||
+ | } | ||
+ | </code> | ||
+ | |||
+ | |Προηγούμενο: [[:java:generic_interfaces | Interfaces ως παραμετρικοί τύποι δεδομένων ]] | [[:toc | Περιεχόμενα ]] | Επόμενο: [[:java:generics_raw | Απλοί παραμετρικοί τύποι δεδομένων (Raw Generic Types) ]] | |