Tree Java

Written by Unknown on Kamis, 30 Mei 2013 at 05.20

XChat box XMy music Hay friends, Dengerin lagu yuks Hehehehe .. XAbout me Hay friends, I Santa Mars Nama asli ane Marsyanta Welcome to my blog I am Indonesian people aye Ingin sekali jadi orang terkenal :D Hopefully all useful Thank you . [Profil Facebook] [Profil Twitter] [Profil Google] [Profil Blogger] [Narsis Dah] XCredit [Click here to begin] [Chat box] [Media Players Music] [About me] [Created by Santa Mars] [Mantap] Coretan Yoni -=[ Structure Data ]=- . Sabtu, 25 Mei 2013 Tree Java Terminologi binary tree binary tree maaf saya menggunakan istilah asing untuk terminologinya. soalnya saya sudah terbiasa pakai istilah ini, kalaupun diterjemahkan kuq hasilnya malah jadi aneh… :) Path Bayangkan seperti orang yang berjalan dari node ke node lain melalui garis yang menghubungkannya. Garis-garis penghubung yang delewati itulah yang dinamakan dengan path. Root Node pada posisi paling atas disebut root. Dalam sebuah tree hanya terdapat satu root saja. Parent Setiap node (kecuali root) mempunyai cabang yang menguhubungkan tepat satu node lain di atasnya. Node di atasnya inilah yang disebut parent. Child Setiap node bisa mempunyai satu atau lebih cabang yang menghubungkan ke node lainnya. Node di bawahnya inilah yang disebut dengan child. Leaf Node yang tidak mempunyai child disebut dengan leaf. Dalam sebuah tree hanya ada satu root saja tetapi bisa mempunyai banyak leaf. Subtree Setiap node bisa dipertimbangkan menjadi root nya subtree, yang terdiri dari beberapa children, dan children nya children. Visiting Sebuah node dikatakan dikunjungi ketika kendali program sampai pada sebuah node, biasanya untuk tujuan menyelesaikan beberapa operasi pada node, seperti mengecek nilai datanya kemudian menampilkannya. Traversing Traverse maksudnya mengunjungi semua node dalam tree untuk tujuan tertentu, misalnya: untuk mengurutkan datanya. Level Level node adalah banyaknya generasi node yang dihitung mulai dari root. Jika kita mengasumsikan bahwa root adalah level 0, maka children adalah level 1, grandchildren adalah level 2, dan seterusnya. Key Medan data dalam sebuah objek biasanya didesain dengan menggunakan sebuah key. Nilai dari key ini digunakan untuk melakukan pencarian data atau operasi lainnya. Tree menggunakan Java Beberapa class untuk mendemonstrasikan binary tree di java Class Node –> untuk membuat node class Node { int iData; // data yang digunakan sebagai kunci double fData; // data lain node childKiri; // node child kiri node childKanan; // node child kanan public void tampilNode() { // (bagian dari tubuh method) } } Class Tree –> membuat susunan Tree nya dimana di dalamnya juga terdapat beberapa method untuk: pencarian node penyisipan node penghapusan node class Tree { private Node root; // satu-satunya data dalam tree public void cari(int key) { tempat penulisan statemen cari } public void sisip(int id, double dd) { tempat penulisan statemen sisip } public void hapus(int id) { tempat penulisan statemen hapus } // klo ada method laen tulis di sini } // akhir dari kelas tree Kirimkan Ini lewat EmailBlogThis!Berbagi ke TwitterBerbagi ke Facebook 0 komentar: Poskan Komentar Buat sebuah Link Posting Lebih Baru Posting Lama Beranda Foto Saya yoni aldin Sparkline 147 © 2012 Coretan Yoni Attention...!!! Ada yang baru nih... Apa..? View this Status Via SM Populer post Struktur Data Sorting and Searching HashMap Map Searching Java Script TreeMap Array Java Stack And Queue Stack and Heap Linked List Struktur Data Explore The Archive ▼ 2013 (11) ▼ Mei (11) Linked List Struktur Data Array Java Stack And Queue Tree Java Stack and Heap TreeMap HashMap Map Searching Java Script Sorting and Searching Struktur Data

linked list

Written by Unknown on at 05.19

Link list adalah desain tempat penyimpanan data yang terdiri dari node-node (simpul-simpul) yang saling terhubung. Link list dapat diilustrasikan seperti kereta api, dimana kereta api terdiri dari gerbong-gerbong yang saling terhubung yang dapat mengangkut penumpang. Gerbong disini setara dengan node dalam link list yang berfungsi untuk menyimpan data. Jika kita menyimpan data 3, 5 dan 7 dalam array, maka ilustrasi tempat penyimpanannya sbb: Dengan 1 nama, array bisa menyimpan data yg bertipe sama. Dimana setiap data mempunyai indeks. Sedangkan jika data tersebut disimpan dalam link list, maka ilustrasi tempat penyimpanannya sbb: Link list tidak mempunyai indeks seperti array. Kita hanya bisa memberi nama node. Akan tetapi, tidak semua node dalam link list mempunyai nama. Sebaiknya kita memberi nama untuk node yang pertama (misal namanya head), dan node yang terakhir (misal namanya tail). Tujuannya untuk memudahkan operasi link list dari depan atau belakang, misal nambah data atau menghapus data. Langkah yang pertama, kita harus mendefinisikan apa itu node. Dalam Java, sebaiknya pendefinisian node ini dibuat dalam sebuah class, misal: Kemudian kita buat design link list dalam class yang lain, misal: * untuk contoh program lengkap ada dalam file. download disini. Operasi-operasi yang bisa dilakukan dalam link list yaitu: Tambah data (insert) Edit data (edit) Hapus data (delete) Pengurutan data (sorting) Pencarian data (searching) Tambah Depan Untuk tambah data dari depan, caranya: Tambah Belakang Untuk tambah data dari belakang, caranya: Hapus Depan Untuk menghapus data dari depan, caranya:

array

Written by Unknown on at 05.17

ARRAY adalah adalah Tipe terstruktur yang terdiri dari sejumlah komponen-komponen yang mempunyai tipe yang sama. Sebelum digunakan, variabel array perlu dideklarasikan terlebih dahulu. Cara mendeklarasikan variabel array sama seperti deklarasi variabel yang lainnya, hanya saja diikuti oleh suatu indek yang menunjukan jumlah maksimum data yang disediakan. Array pada pemrogramman Java, dapat dibagi menjadi 2 bagian besar, yaitu Array Berdimensi Satu dan Array Multidimensi. A. Array Berdimensi Satu Bentuk pendekarasian Array Berdimensi Satu pada pemrograman Java, seperti dibawah ini: tipe_data[] nama_var_array; nama_var_array = new tipe_data[ukuran]; Contoh pendeklarasian : int[] nilai; nilai = new int[10]; a. Memasukan Nilai ke Array Untuk memasukan nilai kedalam elemen array, dengan cara menyebutkan index untuk elemen array tersebut. Index dimulai dari index ke 0, bukan dari index ke 1. nilai[0] = 70; nilai[1] = 60; nilai[2] = 80; b. Mengambil Nilai dari Array Untuk mengambil nilai dari dalam elemen array, dengan cara yang sama seperti memasukan kedalam elemen array, yaitu dengan menyebutkan index dari elemen array tersebut. nilai[0]; nilai[1]; System.out.println("Nilai Elemen : " + nilai[0]); Berikut contoh program array untuk menghitung total nilai dan nilai rata-rata elemen array. /* ---------------------------- Nama File : Array_D1_01.java Author : Frieyadie ------------------------------- */ import java.util.*; class Array_D1_01 { public static void main(String[] args) { int a, n, jml_nil=0; double nil_rata=0; int[] nilai; // deklarasi variabel array nilai = new int[10]; // membuat objek array Scanner input = new Scanner(System.in); System.out.print("Masukkan Banyak Data = "); n = input.nextInt(); System.out.println(""); //Memasukan Data ke Elemen Array for(a=0; a

Stack and Queue

Written by Unknown on at 05.16

Pengertian Stack Stack atau tumpukan adalah suatu stuktur data yang penting dalam pemrograman Bersifat LIFO (Last In First Out) Benda yang terakhir masuk ke dalam stack akan menjadi benda pertama yang dikeluarkan dari stack Contohnya, karena kita menumpuk Compo di posisi terakhir, maka Compo akan menjadi elemen teratas dalam tumpukan. Sebaliknya, karena kita menumpuk Televisi pada saat pertama kali, maka elemen Televisi menjadi elemen terbawah dari tumpukan. Dan jika kita mengambil elemen dari tumpukan, maka secara otomatis akan terambil elemen teratas, yaitu Compo juga. Operasi-operasi/fungsi Stack Push : digunakan untuk menambah item pada stack pada tumpukan paling atas Pop : digunakan untuk mengambil item pada stack pada tumpukan paling atas Clear : digunakan untuk mengosongkan stack IsEmpty : fungsi yang digunakan untuk mengecek apakah stack sudah kosong IsFull : fungsi yang digunakan untuk mengecek apakah stack sudah penuh Stack with Array of Struct Definisikan Stack dengan menggunakan struct Definisikan MAX_STACK untuk maksimum isi stack Buatlah variabel array data sebagai implementasi stack secara nyata Deklarasikan operasi-operasi/function di atas dan buat implemetasinya Deklarasi MAX_STACK #define MAX_STACK 10 //hati-hati mulai dari 0 jadi 0-9 Deklarasi STACK dengan struct dan array data typedef struct STACK{ int top; char data[10][10]; //misalkan : data adalah array of string //berjumlah 10 data, masing-masing string //menampung maksimal 10 karakter }; Deklarasi/buat variabel dari struct STACK tumpuk; Inisialisasi Stack Pada mulanya isi top dengan -1, karena array dalam C dimulai dari 0, yang berarti stack adalah KOSONG! Top adalah suatu variabel penanda dalam STACK yang menunjukkan elemen teratas Stack sekarang. Top Of Stack akan selalu bergerak hingga mencapai MAX of STACK sehingga menyebabkan stack PENUH! Ilustrasi stack pada saat inisialisasi: Fungsi IsFull Untuk memeriksa apakah stack sudah penuh? Dengan cara memeriksa top of stack, jika sudah sama dengan MAX_STACK-1 maka full, jika belum (masih lebih kecil dari MAX_STACK-1) maka belum full Ilustrasi: Fungsi IsEmpty Untuk memeriksa apakah stack masih kosong? Dengan cara memeriksa top of stack, jika masih -1 maka berarti stack masih kosong! Program: Fungsi Push Untuk memasukkan elemen ke stack, selalu menjadi elemen teratas stack Tambah satu (increment) nilai top of stack terlebih dahulu setiap kali ada penambahan elemen stack, asalkan stack masih belum penuh, kemudian isikan nilai baru ke stack berdasarkan indeks top of stack setelah ditambah satu (diincrement) Ilustrasinya: Fungsi Pop Untuk mengambil elemen teratas dari stack. Ambil dahulu nilai elemen teratas stack dengan mengakses top of stack, tampilkan nilai yang akan diambil terlebih dahulu, baru didecrement nilai top of stack sehingga jumlah elemen stack berkurang Ilustrasinya: Programnya: Fungsi Print Untuk menampilkan semua elemen-elemen stack Dengan cara looping semua nilai array secara terbalik, karena kita harusmengakses dari indeks array tertinggi terlebih dahulu baru ke indeks yang kecil! QUEUE DENGAN MENGGUNAKAN ARRAY Queue = Antrian Elemen yang pertama kali masuk ke antrian akan keluar pertama kalinya DEQUEUE adalah mengeluarkan satu elemen dari suatu Antrian Antrian dapat dibuat dengan menggunakan: Liniear Array dan Circular Array QUEUE DENGAN LINIEAR ARRAY Terdapat satu buah pintu masuk di suatu ujung dan satu buah pintu keluar di ujung satunya Sehingga membutuhkan variabel Head dan Tail DEKLARASI QUEUE OPERASI-OPERASI PADA QUEUE - Create() o Untuk menciptakan dan menginisialisasi Queue o Dengan cara membuat Head dan Tail = -1 - IsEmpty() o Untuk memeriksa apakah Antrian sudah penuh atau belum o Dengan cara memeriksa nilai Tail, jika Tail = -1 maka empty o Kita tidak memeriksa Head, karena Head adalah tanda untuk kepala antrian (elemen pertama dalam antrian) yang tidak akan berubahubah o Pergerakan pada Antrian terjadi dengan penambahan elemen Antrian kebelakang, yaitu menggunakan nilai Tail - IsFull() o Untuk mengecek apakah Antrian sudah penuh atau belum o Dengan cara mengecek nilai Tail, jika Tail >= MAX-1 (karena MAX-1 adalah batas elemen array pada C) berarti sudah penuh - Enqueue(data) o Untuk menambahkan elemen ke dalam Antrian, penambahan elemen selalu ditambahkan di elemen paling belakang o Penambahan elemen selalu menggerakan variabel Tail dengan cara increment counter Tail - Dequeue() o Digunakan untuk menghapus elemen terdepan/pertama dari Antrian o Dengan cara mengurangi counter Tail dan menggeser semua elemen antrian kedepan. o Penggeseran dilakukan dengan menggunakan looping - Clear() o Untuk menghapus elemen-elemen Antrian dengan cara membuat Tail dan Head = -1 o Penghapusan elemen-elemen Antrian sebenarnya tidak menghapus arraynya, namun hanya mengeset indeks pengaksesan-nya ke nilai -1 sehingga elemen-elemen Antrian tidak lagi terbaca - Tampil() o Untuk menampilkan nilai-nilai elemen Antrian o Menggunakan looping dari head s/d tail

Stack and Heap

Written by Unknown on at 05.13

XChat box XMy music Hay friends, Dengerin lagu yuks Hehehehe .. XAbout me Hay friends, I Santa Mars Nama asli ane Marsyanta Welcome to my blog I am Indonesian people aye Ingin sekali jadi orang terkenal :D Hopefully all useful Thank you . [Profil Facebook] [Profil Twitter] [Profil Google] [Profil Blogger] [Narsis Dah] XCredit [Click here to begin] [Chat box] [Media Players Music] [About me] [Created by Santa Mars] [Mantap] Coretan Yoni -=[ Structure Data ]=- . Sabtu, 25 Mei 2013 Stack and Heap Dalam java, dikenal 2 buah jenis memory, yaitu : 1. Stack (tempat local variable dan tumpukan method) 2. Heap (tempat instance variable dan object) · Bila ada program berikut [1] : Program xx 1. public class A { 2. B b1 = new B(); 3. String s = "halo"; 4. int i = 10; 5. 6. public static void main(String[] args) { 7. A a = new A(); 8. a.myMethod(); 9. } 10. 11. private void myMethod() { 12. System.out.println(s); 13. } 14. } class B {} Yang terletak di stack : 1. Method main() 2. Method myMethod() 3. Variable reference a (baris 7) Yang terletak di heap : 1. Variable reference b1 (baris 2) 2. Variable reference s (baris 3) 3. Variable i (baris 4) 4. Object dari kelas B (baris 2) 5. Object String dengan nilai “halo” (baris 3) 6. Object dari kelas A (baris 7) Sumber Kirimkan Ini lewat EmailBlogThis!Berbagi ke TwitterBerbagi ke Facebook 0 komentar: Poskan Komentar Buat sebuah Link Posting Lebih Baru Posting Lama Beranda Foto Saya yoni aldin Sparkline 143 © 2012 Coretan Yoni Attention...!!! Ada yang baru nih... Apa..? View this Status Via SM Populer post Struktur Data Sorting and Searching HashMap Map Searching Java Script TreeMap Tree Java Array Java Stack And Queue Explore The Archive ▼ 2013 (11) ▼ Mei (11) Linked List Struktur Data Array Java Stack And Queue Tree Java Stack and Heap TreeMap HashMap Map Searching Java Script Sorting and Searching Struktur Data

TreeMap

Written by Unknown on at 05.11

1. HashMap 2. ThreeMap 3. Map public class TreeMap extends AbstractMap implements SortedMap, Cloneable, Serializable Red-Black tree based implementation of the SortedMap interface. This class guarantees that the map will be in ascending key order, sorted according to the natural order for the key's class (see Comparable), or by the comparator provided at creation time, depending on which constructor is used. This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest's Introduction to Algorithms. Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface. Note that this implementation is not synchronized. If multiple threads access a map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with an existing key is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map: Map m = Collections.synchronizedMap(new TreeMap(...)); The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator throws a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework. Untuk Lebih jelas Klik link ni http://docs.oracle.com/javase/1.5.0/docs/api/java/util/TreeMap.html Since: 1.2 See Also: Map, HashMap, Hashtable, Comparable, Comparator, Collection, Collections.synchronizedMap(Map), Serialized Form

HashMap

Written by Unknown on at 05.07

1. HashMap 2. ThreeMap 3. Map Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time. This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important. An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the capacity is roughly doubled by calling the rehash method. As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur. If many mappings are to be stored in a HashMap instance, creating it with a sufficiently large capacity will allow the mappings to be stored more efficiently than letting it perform automatic rehashing as needed to grow the table. Note that this implementation is not synchronized. If multiple threads access this map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map: Map m = Collections.synchronizedMap(new HashMap(...)); The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs. This class is a member of the Java Collections Framework. Since: 1.2 See Also: Object.hashCode(), Collection, Map, TreeMap, Hashtable, Serialized Form Constructor Summary HashMap() Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75). HashMap(int initialCapacity) Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75). HashMap(int initialCapacity, float loadFactor) Constructs an empty HashMap with the specified initial capacity and load factor. HashMap(MapK ,? extends V> m) Constructs a new HashMap with the same mappings as the specified Map. Method Summary void clear() Removes all mappings from this map. Object clone() Returns a shallow copy of this HashMap instance: the keys and values themselves are not cloned. 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 collection view of the mappings contained in this map. V get(Object key) Returns the value to which the specified key is mapped in this identity hash map, or null if the map contains no mapping for this key. 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. void putAll(MapK ,? extends V> m) Copies all of the mappings from the specified map to this map These mappings will replace any mappings that this map had for any of the keys currently in the specified map. V remove(Object key) Removes the mapping for this key from this map if present. 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. Methods inherited from class java.util.AbstractMap equals, hashCode, toString Methods inherited from class java.lang.Object finalize, getClass, notify, notifyAll, wait, wait, wait Methods inherited from interface java.util.Map equals, hashCode

Map

Written by Unknown on 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

sorting and searching

Written by Unknown on at 05.03

Didalam pemograman Java terdapat dua algoritma yang dapat digunakan dua metode yaitu sorting dan searching. Dibawah ini akan membahas dua algoritma tersebut dan beserta contoh listing pemograman dalam java. 1. Sorting Sorting adalah proses menyusun elemen - elemen dengan tata urut tertentu dan proses tersebut terimplemantasi dalam bermacam aplikasi. Macam - macam algoritma sorting : Insertion Sort Salah satu algoritma sorting yang paling sederhana adalahinsertion sort. Algoritma Insertion sort pada dasarnya memilah data yang akan diurutkan menjadi dua bagian, yang belum diurutkan dan yang sudah diurutkan. Elemen pertama diambil dari bagian arrayyang belum diurutkan dan kemudian diletakan sesuai dengan posisinya pada bagian lain dari array yang telah diurutkan. Langkah ini dilakukan secara berulang hingga tidak ada lagi elemen yang terisisa pada bagian array yang belum diurutkan. Selection Sort Selection Sort adalah memilih elemen dengan nilai yang paling rendah dan menukar elemen yang terpilih dengan elemen ke-i. Nilai dari i dimulai dari 1 ke-n, dimana n adalah jumlah total elemen dikurangi 1. Merge Sort Sebelum pembahasan mengenai algoritma merge sort, akan dijelaskan garis besar dari konsep divide and conquer karena merge sort mengadaptasi pola tersebut. Pola Divide and Conquer Beberapa algoritma mengimplentasikan konsep rekursi untuk menyelesaikan permasalahan. Permasalahan utama kemudian dipecah menjadi sub-masalah, kemudian solusi dari sub-masalah akan membimbing menuju solusi permasalahan utama. Pada setiap tingkatan rekursi, pola tersebut terdiri atas 3 langkah: 1. Divide Memilah masalah menjadi sub masalah. 2. Conquer Selesaikan sub masalah tersebut secara rekursif. Jika sub-masalah tersebut cukup ringkas dan sederhana, pendekatan penyelesaian secara langsung akan lebih efektif. 3. Kombinasi Mengkombinasikan solusi dari sub-masalah, yang akan membimbing menuju penyelesaian atas permasalahan utama. Proses rekursi berhenti jika mencapai elemen dasar. Hal ini terjadi bilamana bagian yang akan diurutkan menyisakan tepat satu elemen. Sisa pengurutan satu elemen tersebut menandakan bahwa bagian tersebut telah terurut sesuai dengan rangkaiannya. Studi Kasus dalam pemograman java dengan menggunakan algoritmaSorting : Class Bubble : Class insert Class Output : 2. Searching Searching merupakan kegiatan untuk menemukan atau mencari suatu data yang ditentukan disuatu tempat, apakah sudah sesuai atau belum. Algoritma searching mempunyai beberapa metode, salah satunya adalah metode pencarian beruntun atau disebut juga denganSequential Search. Sequantial Search adalah metode pencarian yang dimulai dari data elemen pertama. Studi Kasus dalam pemograman java dengan menggunakan algoritmaSearching : Class Searching : Hasil Output In this tutorial, it shows the use of java.lang.Comparable and java.util.Comparator to sort a Java object based on its property value. 1. Sort an Array To sort an Array, use the Arrays.sort(). String[] fruits = new String[] {"Pineapple","Apple", "Orange", "Banana"}; Arrays.sort(fruits); int i=0; for(String temp: fruits){ System.out.println("fruits " + ++i + " : " + temp); } Output fruits 1 : Apple fruits 2 : Banana fruits 3 : Orange fruits 4 : Pineapple 2. Sort an ArrayList To sort an ArrayList, use the Collections.sort(). List fruits = new ArrayList(); fruits.add("Pineapple"); fruits.add("Apple"); fruits.add("Orange"); fruits.add("Banana"); Collections.sort(fruits); int i=0; for(String temp: fruits){ System.out.println("fruits " + ++i + " : " + temp); } Output fruits 1 : Apple fruits 2 : Banana fruits 3 : Orange fruits 4 : Pineapple 3. Sort an Object with Comparable How about a Java Object? Let create a Fruit class: public class Fruit{ private String fruitName; private String fruitDesc; private int quantity; public Fruit(String fruitName, String fruitDesc, int quantity) { super(); this.fruitName = fruitName; this.fruitDesc = fruitDesc; this.quantity = quantity; } public String getFruitName() { return fruitName; } public void setFruitName(String fruitName) { this.fruitName = fruitName; } public String getFruitDesc() { return fruitDesc; } public void setFruitDesc(String fruitDesc) { this.fruitDesc = fruitDesc; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } } To sort it, you may think of Arrays.sort() again, see below example : package com.mkyong.common.action; import java.util.Arrays; public class SortFruitObject{ public static void main(String args[]){ Fruit[] fruits = new Fruit[4]; Fruit pineappale = new Fruit("Pineapple", "Pineapple description",70); Fruit apple = new Fruit("Apple", "Apple description",100); Fruit orange = new Fruit("Orange", "Orange description",80); Fruit banana = new Fruit("Banana", "Banana description",90); fruits[0]=pineappale; fruits[1]=apple; fruits[2]=orange; fruits[3]=banana; Arrays.sort(fruits); int i=0; for(Fruit temp: fruits){ System.out.println("fruits " + ++i + " : " + temp.getFruitName() + ", Quantity : " + temp.getQuantity()); } } } Nice try, but, what you expect the Arrays.sort() will do? You didn’t even mention what to sort in the Fruit class. So, it will hits the following error : Exception in thread "main" java.lang.ClassCastException: com.mkyong.common.Fruit cannot be cast to java.lang.Comparable at java.util.Arrays.mergeSort(Unknown Source) at java.util.Arrays.sort(Unknown Source) To sort an Object by its property, you have to make the Object implement the Comparable interface and override the compareTo() method. Lets see the new Fruit class again. public class Fruit implements Comparable{ private String fruitName; private String fruitDesc; private int quantity; public Fruit(String fruitName, String fruitDesc, int quantity) { super(); this.fruitName = fruitName; this.fruitDesc = fruitDesc; this.quantity = quantity; } public String getFruitName() { return fruitName; } public void setFruitName(String fruitName) { this.fruitName = fruitName; } public String getFruitDesc() { return fruitDesc; } public void setFruitDesc(String fruitDesc) { this.fruitDesc = fruitDesc; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int compareTo(Fruit compareFruit) { int compareQuantity = ((Fruit) compareFruit).getQuantity(); //ascending order return this.quantity - compareQuantity; //descending order //return compareQuantity - this.quantity; } } The new Fruit class implemented the Comparable interface, and overrided the compareTo() method to compare its quantity property in ascending order. The compareTo() method is hard to explain, in integer sorting, just remember this.quantity – compareQuantity is ascending order. compareQuantity – this.quantity is descending order. To understand more about compareTo() method, read this Comparable documentation. Run it again, now the Fruits array is sort by its quantity in ascending order. fruits 1 : Pineapple, Quantity : 70 fruits 2 : Orange, Quantity : 80 fruits 3 : Banana, Quantity : 90 fruits 4 : Apple, Quantity : 100 4. Sort an Object with Comparator How about sorting with Fruit’s “fruitName” or “Quantity”? The Comparable interface is only allow to sort a single property. To sort with multiple properties, you need Comparator. See the new updated Fruit class again : import java.util.Comparator; public class Fruit implements Comparable{ private String fruitName; private String fruitDesc; private int quantity; public Fruit(String fruitName, String fruitDesc, int quantity) { super(); this.fruitName = fruitName; this.fruitDesc = fruitDesc; this.quantity = quantity; } public String getFruitName() { return fruitName; } public void setFruitName(String fruitName) { this.fruitName = fruitName; } public String getFruitDesc() { return fruitDesc; } public void setFruitDesc(String fruitDesc) { this.fruitDesc = fruitDesc; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public int compareTo(Fruit compareFruit) { int compareQuantity = ((Fruit) compareFruit).getQuantity(); //ascending order return this.quantity - compareQuantity; //descending order //return compareQuantity - this.quantity; } public static Comparator FruitNameComparator = new Comparator() { public int compare(Fruit fruit1, Fruit fruit2) { String fruitName1 = fruit1.getFruitName().toUpperCase(); String fruitName2 = fruit2.getFruitName().toUpperCase(); //ascending order return fruitName1.compareTo(fruitName2); //descending order //return fruitName2.compareTo(fruitName1); } }; } The Fruit class contains a static FruitNameComparator method to compare the “fruitName”. Now the Fruit object is able to sort with either “quantity” or “fruitName” property. Run it again. 1. Sort Fruit array based on its “fruitName” property in ascending order. Arrays.sort(fruits, Fruit.FruitNameComparator); Output fruits 1 : Apple, Quantity : 100 fruits 2 : Banana, Quantity : 90 fruits 3 : Orange, Quantity : 80 fruits 4 : Pineapple, Quantity : 70 2. Sort Fruit array based on its “quantity” property in ascending order. Arrays.sort(fruits) Output fruits 1 : Pineapple, Quantity : 70 fruits 2 : Orange, Quantity : 80 fruits 3 : Banana, Quantity : 90 fruits 4 : Apple, Quantity : 100 The java.lang.Comparable and java.util.Comparator are powerful but take time to understand and make use of it, may be it’s due to the lacking of detail example. My thoughts… In future, Arrays class should provides more generic and handy method – Arrays.sort(Object, String, flag). To sort a object array by its “fruitName” in ascending order. Arrays.sort(fruits, fruitName, Arrays.ASCENDING); To sort a object array by its “quantity” in ascending order. Arrays.sort(fruits, quantity, Arrays.DESCENDING);