Map

Written by Unknown on Kamis, 30 Mei 2013 at 05.05

1. HashMap 2. ThreeMap 3. Map Suatu array yang berisi N elemen bisa juga dilihat sebagai asosiasi (pemetaan) antara elemennya dengan bilangan 0, 1, ..., N-1 yang merupakan indeksnya. Jika i adalah salah satu bilangan ini, maka kita bisa mengambil elemen yang dipetakan oleh bilangan i, dan juga kita bisa meletakkan elemen baru pada posisi ke-i. Suatu peta (map) adalah generalisasi dari array. Seperti array, map juga memiliki operasi untuk mengambil dan meletakkan elemen. Akan tetapi pada map, operasi ini tidak dilakukan pada bilangan 0, 1, ... N-1, akan tetapi pada sembarang Object. Beberapa bahasa pemrograman menggunakan istilah array asosiatif (associative array) karena kesamaan perintah dengan array biasa. Pada bahasa pemrograman tersebut, kita bisa menuliskan A["joko"] yang digunakan untuk memetakan "joko" pada suatu elemen di dalam array. Java tidak menggunakan perintah yang sama pada map, akan tetapi idenya serupa : Map adalah seperti array yang indeksnya adalah objek sembarang, bukan integer. Pada map, objek yang digunakan sebagai "indeks" disebut kunci (key). Objek yang ditunjuk oleh indeks tersebut disebut nilai (value). Satu kunci hanya boleh menunjuk pada satu nilai, akan tetapi satu nilai bisa ditunjuk oleh beberapa kunci. Dalam Java, map didefinisikan dalam interface java.util.Map, yang memiliki beberapa metode untuk bekerja dengan map. Jika map adalah variabel dengan tipe Map, maka berikut ini adalah beberapa metodenya : map.get(kunci) -- mengembalikan Object yang ditunjuk oleh kunci. Jika map tidak memiliki nilai yang ditunjuk oleh kunci, maka nilai null akan dikembalikan. Tapi ingat juga bahwa mungkin saja kuncinya ada akan tetapi memang menunjuk pada nilai null. Menggunakan "map.get(kunci)" sama dengan perintah "A[kunci]" pada array A. (Akan tetapi pada map tidak ada pengecualian IndexOutOfBoundsException) map.put(kunci, nilai) -- Mengisi map dengan pasangan kunci dan nilai. Kedua-dua kunci dan nilai bisa berupa objek apa saja. Jika map tersebut telah memiliki kunci maka nilai yang ditunjuk akan diganti dengan yang baru diberikan. Perintah ini mirip dengan "A[kunci] = nilai" pada array. map.putAll(map2) -- jika map2 adalah map lain, maka perintah ini akan mengkopi semua isi pada map2 ke dalam map. map.remove(kunci) -- Jika map memiliki kunci yang menunjuk pada suatu nilai, perintah ini akan menghapus kunci beserta nilai yang ditunjuknya, atau dengan kata lain menghapus pasangan kunci dan nilai pada map sekaligus. map.containsKey(kunci) -- mengembalikan nilai boolean true jika map memiliki kunci yang merujuk pada suatu nilai map.containsValue(nilai) -- mengembalikan nilai boolean true jika map memiliki nilai yang ditunjuk oleh kunci apapun. map.size() -- mengembalikan int yang berisi jumlah pasangan asosiasi pada map. map.isEmpty() -- mengembalikan boolean true jika map tidak berisi pasangan asosiasi apa-apa. map.clear() -- menghapus semua pasangan asosiasi dalam map. Metode put dan get jelas merupakan metode yang paling sering digunakan dalam map. Dalam banyak aplikasi, metode ini mungkin hanya metode ini yang kita butuhkan. Artinya, menggunakan map sama mudahnya dengan menggunakan array biasa. Java memiliki dua kelas yang mengimplementasikan interface Map, yaitu : TreeMap dan HashMap. Dalam TreeMap, pasangan kunci/nilai disimpan secara berurutan dalam pohon terurut, yaitu diurut berdasarkan kuncinya. Supaya bisa bekerja dengan benar, maka hanya objek yang bisa dibandingkan saja yang bisa digunakan sebagai kunci. Artinya kelas kunci harus berupa kelas yang mengimplementasikan interface Comparable, atau Comparator harus diberikan pada konstruktornya pada saat TreeMap dibuat. HashMap tidak menyimpan pasangan kunci/nilai dalam urutan tertentu, sehingga tidak ada batasan objek apa yang bisa disimpan di dalamnya. Hampir semua operasi dapat berjalan lebih cepat pada HashMap dibandingkan dengan TreeMap. Secara umum, lebih baik menggunakan HashMap kecuali kita butuh struktur data dalam urutan tertentu yang hanya bisa dilakukan dengan TreeMap. Atau dengan kata lain, jika kita hanya menggunakan perintah put dan get, gunakan HashMap. Misalnya progrma direktori telefon, yaitu pada kelas BukuTelepon yang memiliki pasangan nama/nomor telepon. Kelas ini memiliki operasi tambahEntri(nama, nomor) dan ambilNomor(nama), di mana nama dan nomor bertipe String. Dalam aplikasi pemrograman sebenarnya, kita tidak perlu lagi membuat kelas baru untuk mengimplementasikan BukuTelepon tersebut, artinya kita bisa langsung menggunakan Map. Akan tetapi menggunakan Map mungkin memiliki sedikit kerugian, karena kita dipaksa harus menggunakan Object bukan String. Jika ini masalahnya, maka kita bisa membuat kelas baru yang menggunakan Map dalam implementasinya, seperti berikut : import java.util.HashMap; public class BukuTelepon { // Menyimpan data telepon private HashMap info = new HashMap(); public void tambahEntri(String nama, String nomor) { // Menyimpan nomor telepon pada nama yang sesuai info.put(nama,nomor); } public String ambilNomor(String nama) { // Mengambil nomor telepon dari nama // Kembalikan null jika tidak ada nomor telepon untuk nama tsb return (String)info.get(nama); } } // akhir kelas BukuTelepon Dalam metode ambilNomor di atas, nilai kembalian dari info.get(nama) di-type-cast ke dalam String. Karena kembalian dari metode get() bertipe Object maka type cast menjadi penting sebelum nilainya bisa digunakan. Dengan "membungkus" Map di dalam kelas BukuTelepon, kita menyembunyikan type-cast dalam implementasinya sehingga interaksi kelas ini dengan kelas lain yang menggunakannya menjadi lebih natural. public interface Map An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value. This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface. The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not. Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on a such a map. All general-purpose map implementation classes should provide two "standard" constructors: a void (no arguments) constructor which creates an empty map, and a constructor with a single argument of type Map, which creates a new map with the same key-value mappings as its argument. In effect, the latter constructor allows the user to copy any map, producing an equivalent map of the desired class. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but all of the general-purpose map implementations in the JDK comply. The "destructive" methods contained in this interface, that is, the methods that modify the map on which they operate, are specified to throw UnsupportedOperationException if this map does not support the operation. If this is the case, these methods may, but are not required to, throw an UnsupportedOperationException if the invocation would have no effect on the map. For example, invoking the putAll(Map) method on an unmodifiable map may, but is not required to, throw the exception if the map whose mappings are to be "superimposed" is empty. Some map implementations have restrictions on the keys and values they may contain. For example, some implementations prohibit null keys and values, and some have restrictions on the types of their keys. Attempting to insert an ineligible key or value throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible key or value may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible key or value whose completion would not result in the insertion of an ineligible element into the map may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface. This interface is a member of the Java Collections Framework. Many methods in Collections Framework interfaces are defined in terms of the equals method. For example, the specification for the contains(Object key) method says: "returns true if and only if this map contain a mapping for a key k such that (key==null ? k==null : key.equals(k))." This specification should not be construed to imply that invoking Map.containsKey with a non-null argument key will cause key.equals(k) to be invoked for any key k. Implementations are free to implement optimizations whereby the equals invocation is avoided, for example, by first comparing the hash codes of the two keys. (The Object.hashCode() specification guarantees that two objects with unequal hash codes cannot be equal.) More generally, implementations of the various Collections Framework interfaces are free to take advantage of the specified behavior of underlying Object methods wherever the implementor deems it appropriate. Since: 1.2 See Also: HashMap, TreeMap, Hashtable, SortedMap, Collection, Set Nested Class Summary static interface Map.Entry<K,V> A map entry (key-value pair). Method Summary void clear() Removes all mappings from this map (optional operation). boolean containsKey(Object key) Returns true if this map contains a mapping for the specified key. boolean containsValue(Object value) Returns true if this map maps one or more keys to the specified value. Set<Map.Entry<K,V>> entrySet() Returns a set view of the mappings contained in this map. boolean equals(Object o) Compares the specified object with this map for equality. V get(Object key) Returns the value to which this map maps the specified key. int hashCode() Returns the hash code value for this map. boolean isEmpty() Returns true if this map contains no key-value mappings. Set<K> keySet() Returns a set view of the keys contained in this map. V put(K key, V value) Associates the specified value with the specified key in this map (optional operation). void putAll(MapK ,? extends V> t) Copies all of the mappings from the specified map to this map (optional operation). V remove(Object key) Removes the mapping for this key from this map if it is present (optional operation). int size() Returns the number of key-value mappings in this map. Collection<V> values() Returns a collection view of the values contained in this map. Map = function() { this.dict = []; this.size = function() { return this.dict.length; } this.get = function(key) { for(i=0;i { duplet = this.dict[i]; if(duplet[0] === key) { return duplet[1]; } } return null; } this.put = function(key, value) { var duplet = this.get(key); if(duplet) { duplet[1] = value; } else { this.dict.push([key, value]); } return this; } this.remove = function(key) { for(i=0;i { duplet = this.dict[i]; if(duplet[0] === key) { this.dict.splice(i,1); return duplet[1]; } } return null; } this.clear = function() { this.dict.splice(0,this.dict.length); } this.values = function() { var values=[]; for(i=0;i { duplet = this.dict[i]; values.push(duplet[1]); } return values; } this.keys = function() { var keys=[]; for(i=0;i { duplet = this.dict[i]; keys.push(duplet[0]); } return keys; } } ////////////////////////////---END---///////////////////////////////////////////////// var Map =new Map(); Map.put(1,"1Number"); Map.put(2,"2Number"); Map.put('1',"1String"); Map.put('2',"2String"); Map.put("one","OneText"); Map.put("two","TwoText"); document.writeln("Map Size= "+Map.size()+"---"); document.writeln("1= "+Map.get(1)+"---"); document.writeln("two= "+Map.get("two")+"---"); document.writeln("keys= "+Map.keys()+"---"); document.writeln("values= "+Map.values()+"---"); Map.remove(2); //remove Map with key 2 document.writeln("afeter removing key 2, keys()= "+Map.keys()+"---"); document.writeln("afeter removing key 2, values()= "+Map.values()+"---"); Map.clear(); document.writeln("Map Size After clearing= "+Map.size()+"---"); Output Map Size= 6 1= 1Number two= TwoText keys= 1,2,1,2,one,two values= 1Number,2Number,1String,2String,OneText,TwoText afeter removing key 2, keys()= 1,1,2,one,two afeter removing key 2, values()= 1Number,1String,2String,OneText,TwoText Map Size After clearing= 0

0 Responses to "Map"