JAVA: Cara Belajar Java Collection

From OnnoWiki
Jump to navigation Jump to search

Di dunia nyata, collection menurut definisi adalah sekelompok artikel/elemen/nilai yang memiliki sifat dan atribut yang serupa. Karena Java adalah Object-Oriented Language, ia meniru dunia nyata. Di Java, Collection adalah sekelompok beberapa object yang disatukan menjadi satu unit. Java Collection adalah topik yang sangat luas dan sebagai pemula mungkin sulit untuk menavigasi jalan saat mempelajarinya. Di sini kita memiliki semua yang perlu Anda ketahui saat memulai dengan Java Collection.


Apakah Collection Framework?

Kita memiliki collection object, sekarang kita membutuhkan cara yang terorganisir untuk menggunakan collection ini, oleh karena itu kita membutuhkan framework. Java Collection framework, pertama kali diperkenalkan di JDK 1.2 ( Java Development Kit 1.2 ), adalah arsitektur yang terdiri dari interface dan class. Dengan kata sederhana, itu seperti struktur rangka untuk komponen yang siap digunakan untuk berbagai kebutuhan pemrograman. Ini juga menawarkan operasi data yang berbeda seperti searching, sorting, insertion, deletion, dan manipulation. Semua class dan interface framework collection digabungkan ke dalam paket java.util.

Hirarki Collection Framework

Collection-Framework-1.png


Collection-Framework-2.png


Class Vs Interface
Class Interface
A class is a user-defined prototype for building objects in Java. An interface is a user-defined blueprint that describes the structure of every class that implements it.
It is used to define objects. It cannot be used to define objects.
A class can have access modifiers public and default. An Interface can have access modifiers public and default.
Classes can be concrete or abstract. All interfaces are abstract.
A class consists of constructors, methods and attributes. The methods are defined in a class. An interface consists attributes and methods. The methods are not defined in an interface, it only contains their signature.


Sekarang setelah kita memiliki konsep dasar dari collection di Java, kita akan memahami setiap komponennya secara detail. Apa saja propertinya dan beberapa contoh koleksi yang paling sering digunakan?

1. Iterable

Interface Iterable adalah sumber/akar/root dari seluruh hierarki collection, yang berarti bahwa setiap class dan interface akan mengimplementasikannya. Fungsi utama dari sebuah iterator adalah untuk memungkinkan pengguna untuk melintasi semua object class collection seolah-olah mereka adalah urutan sederhana dari item data.

2. Collection

Interface Collection meng-extend interface Iterable. Interface collection memiliki method dasar yang diperlukan untuk menggunakan semua collection lain dalam framework untuk add, delete, dan manipulate data. Karena ini adalah interface, ia hanya memiliki signature method ( yaitu <return type> methodName ( ArgumentList ); ) dan tidak ada definisi karena setiap interface atau class yang mengimplementasikan interface ini akan memiliki jenis elemen yang berbeda untuk ditangani. Tetapi karena mereka mengimplementasikan interface ini, ada keseragaman dan struktur untuk koleksi lainnya. Method interface collection koleksi diberikan di bawah ini, semua interface dan class yang meng-extend atau mengimplementasikan interface collection menggunakan method ini bersama dengan method tambahan mereka sendiri khusus untuk mereka.

3. List

List interface meng-extend Collection interface. Elemen-elemen dalam list diurutkan secara beruntun. User dapat menggunakan nomor indeks untuk mengakses elemen tertentu dalam list, artinya, pengguna memiliki kontrol penuh atas elemen mana yang dimasukkan ke dalam list.

3. a) ArrayList

ArrayList class mengimplementasikan List interface. Object dari class ini adalah array dinamis. ArrayList pada dasarnya adalah implementasi list yang dapat diubah ukurannya. Ini mengimplementasikan semua method List dan memungkinkan semua elemen bahkan elemen nol. Object ArrayList memiliki kapasitas, yang awalnya sama dengan ukuran tetapi meningkat secara dinamis saat elemen baru ditambahkan. ArrayList tidak disinkronkan, yang berarti beberapa thread dapat mengaksesnya secara bersamaan. Thread adalah unit flow control sekuensial yang dapat diproses di Sistem Operasi.

Syntax:

ArrayList<?> arrayListName = new ArrayList<?>();

Contoh: kita akan mengambil contoh dan melakukan beberapa operasi dasar pada ArrayList. Di sini kita membuat instance ArrayList bernama intArr. Kita menggunakan method add() untuk menambahkan bilangan integer ke intArr. Class Integer yang digunakan dalam mendeklarasikan intArr adalah class wrapper untuk tipe data dasar int. Class wrapper meng-extend dari class Object dan digunakan agar tipe data dasar kompatibel dengan kelas lain. Selanjutnya, kita mencetak ArrayList di konsol. Kami menggunakan method remove() untuk menghapus elemen dari indeks yang ditentukan. Kami memeriksa apakah sebuah elemen, 25 di sini, ada di intArr dan mencetak pesan yang sesuai. Kemudian kita mengambil elemen pada indeks 1 menggunakan method get(). Seperti yang akan kita amati ketika sebuah elemen dihapus menggunakan method remove(), elemen-elemen lainnya bergeser secara berurutan.

// An example for ArrayList
// All of the classes and
// interfaces of the collection
// framework are bundled into
// the java.util package
import java.util.*;
 
public class BasicArrayList {
 
    // main method
    public static void main(String[] args) {
         
        // Instantiate an ArrayList Object
        // Integer is a wrapper class for
        // the basic datatype int
        ArrayList<Integer> intArr = new ArrayList<Integer>();
         
        // Add elements using add() method
        intArr.add(10);
        intArr.add(12);
        intArr.add(25);
        intArr.add(19);
        intArr.add(11);
        intArr.add(3);
         
        // Print the ArrayList on the console
        System.out.println(intArr);
         
        // Remove elements at index 1 and 4
        intArr.remove(1);
        intArr.remove(4);
         
        // Print the ArrayList on the console
        System.out.println(intArr);
         
        // Check if intArr contains the element 25
        if(intArr.contains(25))
        {
            System.out.println("The ArrayList contains 25");
        }
        else
        {
            System.out.println("No such element exists");
        }
         
        // Use get method to get the element at index 1
        int elementAt1 = intArr.get(1);
        System.out.println("The Element at index 1 now is " + elementAt1);
          
    }
}

Output

[10, 12, 25, 19, 11, 3]
[10, 25, 19, 11]
The ArrayList contains 25
The Element at index 1 now is 25

3. b) Vector

Vector class mengimplementasikan List iterator. Vector instance adalah dynamic array, di mana elemen dapat diakses dengan indeks. Perbedaan antara Vektor dan ArrayList adalah bahwa Vektor disinkronkan.

Syntax:

Vector<?> vectorName = new Vector<?>();

Melalui contoh berikut kita akan mencoba memahami Vector, Dalam code yang diberikan di bawah ini kita telah mendeklarasikan sebuah Vector bernama intVector, kita menggunakan add() untuk menambahkan elemen ke Vector. Method size() memberikan jumlah elemen saat ini yang disimpan dalam Vector. Method remove() digunakan untuk menghapus elemen pada indeks yang ditentukan.

// An example for Vector
import java.util.*;
 
public class VectorExample {
 
    public static void main(String[] args) {
         
        // Instantiate Vector object
        Vector<Integer> intVector = new Vector<Integer>();
         
        // Print the initial size of the Vector
        System.out.println("The initial size of the Vector = " + intVector.size());
        System.out.println();
         
        // Add elements using add method
        intVector.add(11);
        intVector.add(18);
        intVector.add(1);
        intVector.add(87);
        intVector.add(19);
        intVector.add(11);
         
        // Print the Vector on the console
        System.out.println("The Vector intVector : ");
        System.out.println(intVector);
        System.out.println("Size of intVector : " + intVector.size());
         
        System.out.println();
         
        // Remove the element at index 2
        intVector.remove(2);
         
        // Print the vector again on the console
        System.out.println("The Vector intVector after removing element at 2 : ");
        System.out.println(intVector);
         
        System.out.println();
         
        // Clear all elements of the Vector and
        // Print the Vector on the console
        intVector.clear();
        System.out.println("The Vector intVector after using clear : ");
        System.out.println(intVector);
 
    }
 
}

Output

The initial size of the Vector = 0

The Vector intVector : 
[11, 18, 1, 87, 19, 11]
Size of intVector : 6

The Vector intVector after removing element at 2 : 
[11, 18, 87, 19, 11] 

The Vector intVector after using clear : 
[]

3. b) i) Stack

Stack class meng-extend dari Vector class. Stack adalah struktur last-in-first-out (LIFO). Anda dapat memvisualisasikannya sebagai tumpukan buku di atas meja, buku yang disimpan pertama harus diambil terakhir, dan buku yang disimpan di tumpukan terakhir harus diambil terlebih dahulu. Method dasar dari stack class adalah push, pop, peek, empty, dan search.


Syntax:

Stack<?> stackName = new Stack<?>();

Contoh: Mari kita memahami Stack lebih baik dengan sebuah contoh. Dalam code yang diberikan di bawah ini, pertama-tama kita membuat Stack bernama strStack, yang elemennya bertipe String. Elemen ditambahkan menggunakan method push(). Method size() mengembalikan jumlah elemen yang ada di Stack. Method search() digunakan untuk mencari elemen dalam stack. Ini mengembalikan 1-based position jika ditemukan lain -1 dikembalikan untuk menunjukkan tidak ada elemen seperti itu di Stack.

// An example to show workings of a Stack
import java.util.*;
 
public class StackExample {
 
    public static void main(String[] args) {
         
        // Instantiate a Stack named strStack
        Stack<String> strStack = new Stack<String>();
         
        // Add elements using the push() method
        strStack.push("Stack");
        strStack.push("a");
        strStack.push("is");
        strStack.push("This");
         
        // The size() method gives the
        // number of elements in the Stack
        System.out.println("The size of the Stack is : " + strStack.size());
        
        // The search() method is
        // used to search an element
        // it returns the position of
        // the element
        int position = strStack.search("a");
        System.out.println("\nThe string 'a' is at position " + position);
         
        System.out.println("\nThe elements of the stack are : ");
        String temp;
        int num = strStack.size();
         
        for(int i = 1; i <= num; i++)
        {
            // peek() returns the topmost element
            temp = strStack.peek();
            System.out.print(temp + " ");
             
            // pop() removes the topmost element
            strStack.pop();
 
        }
         
    }
 
}

Output

The size of the Stack is : 4

The string 'a' is at position 3

The elements of the stack are : 
This is a Stack

3. c) LinkedList

The LinkedList class implements the List interface as well as the Deque interface. The LinkedList is the class implementation of the linked list data structure, where every element has a pointer to the next element forming a link. Since each element has an address of the next element, the linked list elements, referred to as nodes, can be stored at non-contiguous locations in memory.

Kelas LinkedList mengimplementasikan antarmuka Daftar serta antarmuka Deque. LinkedList adalah implementasi kelas dari struktur data daftar tertaut, di mana setiap elemen memiliki penunjuk ke elemen berikutnya yang membentuk tautan. Karena setiap elemen memiliki alamat elemen berikutnya, elemen daftar tertaut, yang disebut sebagai node, dapat disimpan di lokasi yang tidak bersebelahan dalam memori.


Syntax:

LinkedList<?> linkedListName = new LinkedList<?>();

Let us take an example to understand LinkedList. In the code given below, we instantiate a LinkedList named strLinkedList. The add() method is used to add elements and remove() method to remove elements. The retrieval of the elements is done using get() method.

Mari kita ambil contoh untuk memahami LinkedList. Dalam kode yang diberikan di bawah ini, kami membuat instance LinkedList bernama strLinkedList. Metode add() digunakan untuk menambahkan elemen dan metode remove() untuk menghapus elemen. Pengambilan elemen dilakukan dengan menggunakan metode get().


// An example for the LinkedList
import java.util.*;
 
public class LinkedListExample {
     
    public static void main(String[] args) {
         
        // Instantiate LinkedList named strLinkedList
        LinkedList<String> strLinkedList = new LinkedList<String>();
         
        // Add elements to the LinkedList using add()
        strLinkedList.add("This");
        strLinkedList.add("is");
        strLinkedList.add("a");
        strLinkedList.add("LinkedList");
         
        // The elements are retrieved using the get() method
        System.out.println("The contents of strLinkedList : ");
        for(int i = 0; i < strLinkedList.size(); i++)
        {
            System.out.print(strLinkedList.get(i) + " ");
        }
         
        // The elements are removed using remove()
        strLinkedList.remove(0);
        strLinkedList.remove(1);
         
        System.out.println("\n\nThe contents of strLinkedList after remove operation : ");
        for(int i = 0; i < strLinkedList.size(); i++)
        {
            System.out.print(strLinkedList.get(i) + " ");
        }
         
    }
 
}

Output

The contents of strLinkedList : 
This is a LinkedList 

The contents of strLinkedList after remove operation : 
is LinkedList

4. Queue

The Queue interface extends the Collection interface. Queue is the interface implementation of the queue data structure. Since Queue in java is an interface it doesn’t have a definition of the methods only their signatures. Queue is typically a first-in-first-out ( FIFO ) structure, though that is not the case for PriorityQueue. You may visualize it as a queue of people at a counter, the person who enters first gets services first and leaves first.

Antarmuka Antrian memperluas antarmuka Koleksi. Antrian adalah implementasi antarmuka dari struktur data antrian. Karena Antrian di java adalah antarmuka, ia tidak memiliki definisi metode hanya tanda tangannya. Antrian biasanya merupakan struktur first-in-first-out ( FIFO ), meskipun itu tidak berlaku untuk PriorityQueue. Anda dapat memvisualisasikannya sebagai antrian orang di konter, orang yang masuk lebih dulu mendapat layanan terlebih dahulu dan pergi lebih dulu.


4. a) PriorityQueue

The PriorityQueue class implements the Queue interface. The elements of a PriorityQueue are either ordered in natural order or in an order specified by a Comparator, which depends on the constructor used. The PriorityQueue is unbounded but there is a capacity that dictates the size of the array in which the elements are stored. The initial capacity is equal to the size of the array but as new elements are added it expands dynamically.

Kelas PriorityQueue mengimplementasikan antarmuka Antrian. Elemen-elemen dari PriorityQueue diurutkan dalam urutan alami atau dalam urutan yang ditentukan oleh Pembanding, yang bergantung pada konstruktor yang digunakan. PriorityQueue tidak terbatas tetapi ada kapasitas yang menentukan ukuran larik tempat elemen disimpan. Kapasitas awal sama dengan ukuran larik tetapi ketika elemen baru ditambahkan, ia berkembang secara dinamis.


Syntax:

PriorityQueue<?> priorityQueueName = new PriorityQueue<?>();

Let us understand PriorityQueue better with an example. In the code given below we instantiate an object of PriorityQueue named intPriorityQueue, since no Comparator is specified in the constructor the elements of this PriorityQueue will be naturally ordered. The add() method is used to add elements and remove() is used to remove a single instance of the specified element. The peek() method is implemented from the Queue interface and it returns the element at the head of the PriorityQueue. The poll() method however removes the element at the head of the PriorityQueue and returns it.


Mari kita memahami PriorityQueue lebih baik dengan sebuah contoh. Dalam kode yang diberikan di bawah ini kami membuat instance objek PriorityQueue bernama intPriorityQueue, karena tidak ada Pembanding yang ditentukan dalam konstruktor, elemen PriorityQueue ini akan diurutkan secara alami. Metode add() digunakan untuk menambahkan elemen dan remove() digunakan untuk menghapus satu instance dari elemen yang ditentukan. Metode peek() diimplementasikan dari antarmuka Antrian dan mengembalikan elemen di kepala PriorityQueue. Namun metode poll() menghapus elemen di kepala PriorityQueue dan mengembalikannya.


// An example for PriorityQueue
import java.util.*;
 
public class PriorityQueueExample {
 
    public static void main(String[] args) {
     
        // Instantiate PriorityQueue object named intPriorityQueue
        PriorityQueue<Integer> intPriorityQueue = new PriorityQueue<Integer>();
         
        // Add elements using add()
        intPriorityQueue.add(17);
        intPriorityQueue.add(20);
        intPriorityQueue.add(1);
        intPriorityQueue.add(13);
        intPriorityQueue.add(87);
         
        // Print the contents of PriorityQueue
        System.out.println("The contents of intPriorityQueue : ");
        System.out.println(intPriorityQueue);
         
        // The peek() method is used to retrieve
          // the head of the PriorityQueue
        System.out.println("\nThe head of the PriorityQueue : " + intPriorityQueue.peek());
         
        // The remove() method is used
        // to remove a single instance
        // of the specified object
        intPriorityQueue.remove(17);
         
        // Print the contents of PriorityQueue
        System.out.println("\nThe contents of intPriorityQueue after removing 17 : ");
        System.out.println(intPriorityQueue);
         
        // The poll() method is used
        // to retrieve and remove the
        // element at the head of the PriorityQueue
        Integer head = intPriorityQueue.poll();
        System.out.println("\nThe head of the PriorityQueue was : " + head);
         
        // Print the contents of PriorityQueue
        System.out.println("\nThe contents of intPriorityQueue after poll : ");
        System.out.println(intPriorityQueue);
    }
 
}

Output

The contents of intPriorityQueue : 
[1, 13, 17, 20, 87]

The head of the PriorityQueue : 1 

The contents of intPriorityQueue after removing 17 : 
[1, 13, 87, 20]

The head of the PriorityQueue was : 1

The contents of intPriorityQueue after poll : 
[13, 20, 87]

5. Deque

The Deque interface extends the Queue interface. The Deque is an implementation of the double-ended queue data structure, which is a linear structure where insertion and deletion can be done at both ends of the queue. The Deque interface supports deques that have capacity restrictions, as well as that, have no fixed limit. Deque can be used as a last-in-first-out ( LIFO ) as well as a first-in-first-out ( FIFO ) structure.

Antarmuka Deque memperluas antarmuka Antrian. Deque merupakan implementasi dari struktur data antrian berujung ganda, yaitu struktur linier dimana penyisipan dan penghapusan dapat dilakukan pada kedua ujung antrian. Antarmuka Deque mendukung deques yang memiliki batasan kapasitas, serta yang tidak memiliki batas tetap. Deque dapat digunakan sebagai struktur last-in-first-out (LIFO) serta first-in-first-out (FIFO).


5. a) ArrayDeque

The ArrayDeque class implements the Deque interface. ArrayDeque is a re-sizable implementation of Deque, it has no fixed capacity but increases as required. The ArrayDeque can be used as a stack, and it is faster compared to the Stack class. ArrayDeque is not thread-safe and it does not allow concurrent access by different threads.


Kelas ArrayDeque mengimplementasikan antarmuka Deque. ArrayDeque adalah implementasi Deque yang cukup besar, tidak memiliki kapasitas tetap tetapi meningkat sesuai kebutuhan. ArrayDeque dapat digunakan sebagai tumpukan, dan lebih cepat dibandingkan dengan kelas Stack. ArrayDeque tidak thread-safe dan tidak mengizinkan akses bersamaan oleh thread yang berbeda.

Syntax:

ArrayDeque<?> arrayDequeName = new ArrayDeque<?>();

6. Set

The Set interface extends the Collection interface. The Set is a structure that models the mathematical definition of a set. It is a collection of objects and no duplicate objects are allowed. The Set allows at most one null element.

Antarmuka Set memperluas antarmuka Koleksi. Himpunan adalah struktur yang memodelkan definisi matematis dari suatu himpunan. Ini adalah kumpulan objek dan tidak ada objek duplikat yang diizinkan. Set memungkinkan paling banyak satu elemen null.


6. a) HashSet

The HashSet class implements the Set interface. In a HashSet, the order of the elements may not be the same as the order of insertion. When an element is added into the HashSet a HashCode is calculated and the element is added to the appropriate bucket ( a bucket is a slot in any Hash structure ). A good HashSet algorithm will uniformly distribute the elements so that the time performance of the structure remains constant. A constant-time performance means it takes constant time for basic operations like insert, deletes, and search.

Kelas HashSet mengimplementasikan antarmuka Set. Dalam HashSet, urutan elemen mungkin tidak sama dengan urutan penyisipan. Ketika sebuah elemen ditambahkan ke dalam HashSet, sebuah HashCode dihitung dan elemen tersebut ditambahkan ke ember yang sesuai (sebuah ember adalah slot dalam struktur Hash apa pun). Algoritma HashSet yang baik akan mendistribusikan elemen secara seragam sehingga kinerja waktu struktur tetap konstan. Performa waktu konstan berarti dibutuhkan waktu yang konstan untuk operasi dasar seperti menyisipkan, menghapus, dan mencari.


6. b) LinkedHashSet

LinkedHashSet implements the Set interface. The LinkedHashSet is very similar to the HashSet with the difference being that for every bucket the structure uses to store elements is a doubly-linked list. The LinkedHashSet ordering is better compared to HashSet without any additional costs.

Let us take an example to understand HashSet and LinkedHashSet. In the code given below, we instantiate a HashSet named strHashSet, using add() method add elements to the HashSet. The hasNext() method and next() method are methods of the Iterable interface that are used to check if there is the next element and to retrieve the next element respectively in any Collection. Using the constructor of the LinkedHashSet, all of the elements of the HashSet are added to it. An Iterator is created to traverse through it and using it the elements are printed on the console.

LinkedHashSet mengimplementasikan antarmuka Set. LinkedHashSet sangat mirip dengan HashSet dengan perbedaan bahwa untuk setiap bucket yang digunakan struktur untuk menyimpan elemen adalah daftar yang ditautkan ganda. Pemesanan LinkedHashSet lebih baik dibandingkan dengan HashSet tanpa biaya tambahan.

Mari kita ambil contoh untuk memahami HashSet dan LinkedHashSet. Dalam kode yang diberikan di bawah ini, kami membuat instance HashSet bernama strHashSet, menggunakan metode add() menambahkan elemen ke HashSet. Metode hasNext() dan metode next() adalah metode antarmuka Iterable yang digunakan untuk memeriksa apakah ada elemen berikutnya dan untuk mengambil elemen berikutnya masing-masing dalam Koleksi apa pun. Menggunakan konstruktor LinkedHashSet, semua elemen HashSet ditambahkan ke dalamnya. Iterator dibuat untuk melintasinya dan menggunakannya elemen dicetak di konsol.


// An example for HashSet and LinkedHashSet
import java.util.*;
 
public class HashSetAndLinkedHashSet {
 
    public static void main(String[] args) {
         
        /*-----------HashSet-------------*/
         
        // Instantiate a HashSet object named strHashSet
        HashSet<String> strHashSet = new HashSet<String>();
         
        // Add elements using add()
        strHashSet.add("This");
        strHashSet.add("is");
        strHashSet.add("a");
        strHashSet.add("HashSet");
         
        // Create an Iterator to traverse through the HashSet
        Iterator<String> hsIterator = strHashSet.iterator();
         
        // Print all the elements of the HashSet
        System.out.println("Contents of HashSet : ");
        while(hsIterator.hasNext())
        {
            System.out.print(hsIterator.next() + " ");
        }
 
        /*---------LinkedHashSet----------*/
         
        // Instantiate an object of LinkedHashSet named strLinkedHashSet
        // Pass the name of the HashSet created earlier to copy all of the contents
        // of the HashSet to the LinkedHashSet using a constructor
        LinkedHashSet<String> strLinkedHashSet = new LinkedHashSet<String>(strHashSet);
         
        // Create an Iterator to traverse through the LinkedHashSet
        Iterator<String> lhsIterator = strLinkedHashSet.iterator();
         
        // Print all the elements of the LinkedHashSet
        System.out.println("\n\nContents of LinkedHashSet : ");
        while(lhsIterator.hasNext())
        {
            System.out.print(lhsIterator.next() + " ");
        }
         
    }
 
}

Output

Contents of HashSet : 
a This is HashSet 

Contents of LinkedHashSet : 
a This is HashSet 

7. SortedSet

The SortedSet interface extends the Set interface. The SortedSet provides a complete ordering of the elements. The default ordering is by Natural order else it is ordered by a Comparator specified at the time of construction. The traversing typically is in ascending order of elements.

Antarmuka SortedSet memperluas antarmuka Set. SortedSet menyediakan urutan elemen yang lengkap. Urutan default adalah dengan urutan Alami, selain itu dipesan oleh Pembanding yang ditentukan pada saat konstruksi. Pelintasan biasanya dalam urutan elemen yang menaik.

8. NavigableSet

The NavigableSet interface extends from the SortedSet interface. In addition to the methods of the SortedSet, NavigableSet has navigation methods that give closest matches such as floor, ceiling, lower and higher. A NavigableSet can be traversed in ascending and descending order. Although it allows null element implementations it is discouraged as these implementations can give ambiguous results.

Antarmuka NavigableSet meluas dari antarmuka SortedSet. Selain metode SortedSet, NavigableSet memiliki metode navigasi yang memberikan kecocokan terdekat seperti lantai, langit-langit, bawah dan tinggi. Sebuah NavigableSet dapat dilalui dalam urutan menaik dan menurun. Meskipun memungkinkan implementasi elemen nol, hal itu tidak disarankan karena implementasi ini dapat memberikan hasil yang ambigu.

8. a) TreeSet

The TreeSet class implements the Navigable interface. The TreeSet as the name suggests uses a tree structure to store elements and a set to order the elements. The ordering is either natural ordering or ordering by the Comparator specified at the time construction. The TreeSet is unsynchronized, which is if multiple threads want to access it at the same time we need to synchronize it externally.

Kelas TreeSet mengimplementasikan antarmuka Navigable. TreeSet seperti namanya menggunakan struktur pohon untuk menyimpan elemen dan satu set untuk mengurutkan elemen. Pemesanan tersebut dapat berupa pemesanan alami atau pemesanan oleh Pembanding yang ditentukan pada saat konstruksi. TreeSet tidak disinkronkan, yaitu jika beberapa utas ingin mengaksesnya secara bersamaan, kita perlu menyinkronkannya secara eksternal.

Syntax:

TreeSet<?> treeSetName = new TreeSet<?>();

Let us take an example to understand TreeSet better. In the code given below, we instantiate an object named intTreeSet. As you can observe the order in this TreeSet is natural ordering and no duplicate elements are allowed. The add() method is used to add the elements and remove() method is used to delete elements.

Mari kita ambil contoh untuk memahami TreeSet dengan lebih baik. Dalam kode yang diberikan di bawah ini, kami membuat instance objek bernama intTreeSet. Seperti yang Anda amati, urutan di TreeSet ini adalah urutan alami dan tidak ada elemen duplikat yang diizinkan. Metode add() digunakan untuk menambahkan elemen dan metode remove() digunakan untuk menghapus elemen.


// An example for TreeSet
import java.util.*;
 
public class TreeSetExample {
 
    public static void main(String[] args) {
         
        // Instantiate an object of TreeSet named intTreeSet
        TreeSet<Integer> intTreeSet = new TreeSet<Integer>();
         
        // Add elements using add()
        intTreeSet.add(18);
        intTreeSet.add(13);
        intTreeSet.add(29);
        intTreeSet.add(56);
        intTreeSet.add(73);
         
        // Try to add a duplicate
        // Observe output as it will not be added
        intTreeSet.add(18);
         
        // Print the TreeSet on the console
        System.out.println("The contents of intTreeSet : ");
        System.out.println(intTreeSet);
         
        // Remove 18 using remove()
        if(intTreeSet.remove(18))
        {
            System.out.println("\nElement 18 has been removed");
        }
        else
        {
            System.out.println("\nNo such element exists");
        }
 
        // Try to remove a non-existent element
        if(intTreeSet.remove(12))
        {
            System.out.println("\nElement 18 has been removed");
        }
        else
        {
            System.out.println("\nNo such element exists");
        }
         
        System.out.println();
         
        // Print the TreeSet on the console
        System.out.println("The contents of intTreeSet : ");
        System.out.println(intTreeSet);
 
    }
 
}

Output

The contents of intTreeSet : 
[13, 18, 29, 56, 73]

Element 18 has been removed

No such element exists

The contents of intTreeSet : 
[13, 29, 56, 73]

9. Map

The Map interface is a structure that maps a key to every value. A Map does not allow duplicate elements as one key cannot have multiple mappings. A Map has three different views, a Set view of the keys, a Set view of key-value mappings, and a Collection view of the values. The methods of the Map interface are given below, every class that implements Map must provide definitions for these methods.

Antarmuka Peta adalah struktur yang memetakan kunci ke setiap nilai. Peta tidak mengizinkan elemen duplikat karena satu kunci tidak dapat memiliki banyak pemetaan. Peta memiliki tiga tampilan berbeda, tampilan Kumpulan kunci, tampilan Kumpulan pemetaan nilai kunci, dan tampilan Kumpulan nilai. Metode antarmuka Peta diberikan di bawah ini, setiap kelas yang mengimplementasikan Peta harus memberikan definisi untuk metode ini.


9. a) HashMap

The HashMap class implements the Map interface. For every entry in a HashMap, a hashCode is computed and this entry is inserted into the bucket with the hashCode value as its index. Every entry is a key-value pair. A bucket in a HashMap may contain more than one entry. A good HashMap algorithm will try to uniformly distribute the elements in the HashMap. HashMap has constant time performance for basic retrieval, insertion, deletion, and manipulation operations. The two most important factors that affect the performance of a HashMap are initial capacity and load factor. The number of buckets is the capacity and the measure of when to increase this capacity is load factor. The HashMap is faster compared to a HashTable.

Kelas HashMap mengimplementasikan antarmuka Peta. Untuk setiap entri dalam HashMap, kode hash dihitung dan entri ini dimasukkan ke dalam ember dengan nilai kode hash sebagai indeksnya. Setiap entri adalah pasangan nilai kunci. Bucket di HashMap dapat berisi lebih dari satu entri. Algoritma HashMap yang baik akan mencoba mendistribusikan elemen-elemen dalam HashMap secara seragam. HashMap memiliki kinerja waktu yang konstan untuk pengambilan dasar, penyisipan, penghapusan, dan operasi manipulasi. Dua faktor terpenting yang mempengaruhi kinerja HashMap adalah kapasitas awal dan faktor beban. Jumlah ember adalah kapasitas dan ukuran kapan untuk meningkatkan kapasitas ini adalah faktor beban. HashMap lebih cepat dibandingkan dengan HashTable.


Syntax:

HashMap<? , ?> hashMapName = new HashMap<? , ?>();

9. b) Hashtable

The Hashtable class implements the Map interface. The Hashtable has key-value pairs as its elements. For effective implementation of the hashtable, the keys must be unique. A Hashtable is very similar to a Hashtable, but Hashtable is synchronous. A good Hashtable algorithm will try to uniformly distribute the elements in the Hashtable. Hashtable has constant time performance for basic retrieval, insertion, deletion, and manipulation operations. The two most important factors that affect the performance of a Hashtable are initial capacity and load factor. The number of buckets is the capacity and the measure of when to increase this capacity is load factor.

Kelas Hashtable mengimplementasikan antarmuka Peta. Hashtable memiliki pasangan nilai kunci sebagai elemennya. Untuk implementasi hashtable yang efektif, kuncinya harus unik. Hashtable sangat mirip dengan Hashtable, tetapi Hashtable sinkron. Algoritma Hashtable yang baik akan mencoba mendistribusikan elemen-elemen dalam Hashtable secara seragam. Hashtable memiliki kinerja waktu yang konstan untuk pengambilan dasar, penyisipan, penghapusan, dan operasi manipulasi. Dua faktor terpenting yang mempengaruhi kinerja Hashtable adalah kapasitas awal dan faktor beban. Jumlah ember adalah kapasitas dan ukuran kapan untuk meningkatkan kapasitas ini adalah faktor beban.


Syntax:

HashTable<? , ?> hashTableName = new HashTable<? , ?>();

9. c) LinkedHashMap

The LinkedHashMap class implements the Map interface. A LinkedHashMap is a hash map linked list implementation of a map. Every entry in the LinkedHashMap has a doubly-linked list running through it. This linked list defines the iteration order that is the order of the keys inserted into the LinkedHashMap. Like all implementations of Map, the elements of the LinkedHashMap are key-value pairs.

Kelas LinkedHashMap mengimplementasikan antarmuka Peta. LinkedHashMap adalah implementasi daftar tertaut peta hash dari sebuah peta. Setiap entri di LinkedHashMap memiliki daftar tertaut ganda yang melewatinya. Daftar tertaut ini mendefinisikan urutan iterasi yang merupakan urutan kunci yang dimasukkan ke dalam LinkedHashMap. Seperti semua implementasi Peta, elemen LinkedHashMap adalah pasangan nilai kunci.

Syntax:

LinkedHashMap<? , ?> linkedHashMapName = new LinkedHashMap<? , ?>();

Let us take an example to understand all of the Map implementations. In the code given below, we add elements using put() method to all of the HashMap, Hashtable, and LinkedHashMap. As put() is a method of the Map interface, therefore, is implemented by all three of these classes. As you can observe the insertion order of Hashtable is not the same as the internal ordering, therefore it is nondeterministic. When we try to insert a duplicate key the old value is replaced in all three. And When we try to insert a duplicate value with a different key it is added as a new entry. Basically this is to depict that we can have duplicate values but not duplicate keys.

Mari kita ambil contoh untuk memahami semua implementasi Peta. Dalam kode yang diberikan di bawah ini, kami menambahkan elemen menggunakan metode put() ke semua HashMap, Hashtable, dan LinkedHashMap. Karena put() adalah metode antarmuka Peta, oleh karena itu, diimplementasikan oleh ketiga kelas ini. Seperti yang Anda amati, urutan penyisipan Hashtable tidak sama dengan urutan internal, oleh karena itu nondeterministik. Saat kami mencoba memasukkan kunci duplikat, nilai lama diganti di ketiganya. Dan ketika kami mencoba memasukkan nilai duplikat dengan kunci yang berbeda, itu ditambahkan sebagai entri baru. Pada dasarnya ini untuk menggambarkan bahwa kita dapat memiliki nilai duplikat tetapi tidak menggandakan kunci.


// An example for HashMap,
// Hashtable and LinkedHashMap
import java.util.*;
 
public class MapImplementaionExample {
 
    public static void main(String[] args) {
         
        /*--------------HashMap---------------*/
         
        // Instantiate an object of HashMap named hashMap
        HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
         
        // Add elements using put()
        hashMap.put(1, "This");
        hashMap.put(2, "is");
        hashMap.put(3, "HashMap");
         
        // Print the HashMap contents on the console
        System.out.println("Contents of hashMap : ");
        System.out.print(hashMap.entrySet());
         
        // Add a duplicate key
        hashMap.put(3, "Duplicate");
         
        // Add a duplicate value
        hashMap.put(4, "This");
         
        // Print the HashMap contents on the console
        System.out.println("\nContents of hashMap after adding duplicate : ");
        System.out.print(hashMap.entrySet());
         
        /*--------------Hashtable----------------*/
         
        // Instantiate an object of Hashtable named hashTable
        Hashtable<Integer, String> hashTable = new Hashtable<Integer, String>();
         
        // Add elements using put()
        hashTable.put(11, "This");
        hashTable.put(12, "is");
        hashTable.put(13, "Hashtable");
         
        // Print the Hashtable contents on the console
        System.out.println("\n\nContents of hashTable : ");
        System.out.print(hashTable.entrySet());
 
        // Add a duplicate key
        hashTable.put(11, "Duplicate");
         
        // Add a duplicate value
        hashTable.put(14, "is");
         
        // Print the Hashtable contents on the console
        System.out.println("\nContents of hashTable after adding duplicate : ");
        System.out.print(hashTable.entrySet());
         
        /*---------------LinkedHashMap---------------*/
         
        // Instantiate an object of LinkedHashMap named linkedHashMape
        LinkedHashMap<Integer, String> linkedHashMap = new LinkedHashMap<Integer, String>();
         
        // Add elements using put()
        linkedHashMap.put(21, "This");
        linkedHashMap.put(22, "is");
        linkedHashMap.put(23, "LinkedHashMap");
         
        // Print the LinkedHashMap contents on the console
        System.out.println("\n\nContents of linkedHashMap : ");
        System.out.print(linkedHashMap.entrySet());
         
        // Add a duplicate key
        linkedHashMap.put(22, "Duplicate");
         
        // Add a duplicate value
        linkedHashMap.put(24, "This");
         
        // Print the LinkedHashMap contents on the console
        System.out.println("\nContents of linkedHashMap after adding duplicate : ");
        System.out.print(linkedHashMap.entrySet());
    }
}

Output

Contents of hashMap : 
[1=This, 2=is, 3=HashMap]
Contents of hashMap after adding duplicate : 
[1=This, 2=is, 3=Duplicate, 4=This] 

Contents of hashTable : 
[13=Hashtable, 12=is, 11=This]
Contents of hashTable after adding duplicate : 
[14=is, 13=Hashtable, 12=is, 11=Duplicate]

Contents of linkedHashMap : 
[21=This, 22=is, 23=LinkedHashMap]
Contents of linkedHashMap after adding duplicate : 
[21=This, 22=Duplicate, 23=LinkedHashMap, 24=This]

10. SortedMap

The SortedMap interface extends the Map interface with an added stipulation of a total order of keys. The keys are either ordered by natural ordering or by a Comparator specified at the time of construction, depending on the constructor used. All of the keys must be comparable.

Antarmuka SortedMap memperluas antarmuka Peta dengan ketentuan tambahan dari urutan total kunci. Kunci diurutkan dengan urutan alami atau oleh Pembanding yang ditentukan pada saat konstruksi, tergantung pada konstruktor yang digunakan. Semua kunci harus sebanding.


10. a) TreeMap

The TreeMap class implements the SortedMap interface. The TreeMap class uses a red-black tree structure for storage and a map for ordering the elements. Every element is a key-value pair. This implementation gives a guaranteed log(n) time cost for basic operations.

Kelas TreeMap mengimplementasikan antarmuka SortedMap. Kelas TreeMap menggunakan struktur pohon merah-hitam untuk penyimpanan dan peta untuk memesan elemen. Setiap elemen adalah pasangan nilai kunci. Implementasi ini memberikan jaminan biaya waktu log(n) untuk operasi dasar.

Syntax:

TreeMap<? , ?> treeMapName = new TreeMap<? , ?>();

Let us take an example to understand the basics of TreeMap. In the code given below, we instantiate an object of the TreeMap object named treeMap. Add elements using put() method. When we try to add a duplicate key with a different value the older instance is replaced with the new value associated with this key. But when we try to add a duplicate value with a new key it is taken as a different entry.

Mari kita ambil contoh untuk memahami dasar-dasar TreeMap. Dalam kode yang diberikan di bawah ini, kita membuat instance objek dari objek TreeMap bernama treeMap. Tambahkan elemen menggunakan metode put(). Saat kami mencoba menambahkan kunci duplikat dengan nilai yang berbeda, instance yang lebih lama diganti dengan nilai baru yang terkait dengan kunci ini. Tetapi ketika kami mencoba menambahkan nilai duplikat dengan kunci baru, itu diambil sebagai entri yang berbeda.

// An example of TreeMap
import java.util.*;
 
public class TreeMapExample {
 
    public static void main(String[] args) {
         
        // Instantiate an object of TreeMap named treeMap
        TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();
         
        // Add elements using put()
        treeMap.put(1, "This");
        treeMap.put(2, "is");
        treeMap.put(3, "TreeMap");
         
        // Print the contents of treeMap on the console
        System.out.println("The contents of treeMap : ");
        System.out.println(treeMap);
         
        // Add a duplicate key
        treeMap.put(1, "Duplicate");
         
        // Add a duplicate value
        treeMap.put(4, "is");
         
        // Print the contents of treeMap on the console
        System.out.println("\nThe contents of treeMap after adding duplicates : ");
        System.out.println(treeMap);
    }
}

Output

The contents of treeMap : 
{1=This, 2=is, 3=TreeMap}

The contents of treeMap after adding duplicates : 
{1=Duplicate, 2=is, 3=TreeMap, 4=is}

Referensi