0% menganggap dokumen ini bermanfaat (0 suara)
43 tayangan42 halaman

Diagram Kerangka Koleksi Java

Dokumen tersebut membahas tentang struktur data koleksi dalam bahasa pemrograman Java. Koleksi merupakan kerangka kerja yang menyediakan arsitektur untuk menyimpan dan memanipulasi kelompok objek. Kerangka koleksi Java mencakup berbagai antarmuka dan kelas untuk mewakili koleksi seperti list, set, dan map."

Diunggah oleh

Bimo Valerian
Hak Cipta
© All Rights Reserved
Kami menangani hak cipta konten dengan serius. Jika Anda merasa konten ini milik Anda, ajukan klaim di sini.
Format Tersedia
Unduh sebagai DOCX, PDF, TXT atau baca online di Scribd
0% menganggap dokumen ini bermanfaat (0 suara)
43 tayangan42 halaman

Diagram Kerangka Koleksi Java

Dokumen tersebut membahas tentang struktur data koleksi dalam bahasa pemrograman Java. Koleksi merupakan kerangka kerja yang menyediakan arsitektur untuk menyimpan dan memanipulasi kelompok objek. Kerangka koleksi Java mencakup berbagai antarmuka dan kelas untuk mewakili koleksi seperti list, set, dan map."

Diunggah oleh

Bimo Valerian
Hak Cipta
© All Rights Reserved
Kami menangani hak cipta konten dengan serius. Jika Anda merasa konten ini milik Anda, ajukan klaim di sini.
Format Tersedia
Unduh sebagai DOCX, PDF, TXT atau baca online di Scribd

MODUL PERKULIAHAN

Struktur Data
Bahasa Pemrograman Java

Tim Penyusun: DIII Teknik Informatika Modul

Ovide Decroly Wisnu Ardhi, S.T., [Link] FMIPA Universitas Sebelas Maret 02 Collection

MATERI KOMPETENSI
Konsep dasar array Mampu menggunakan IDE
NetBeans
Membuat array data primitif &
objek Mampu membuat array data
primitif & objek
Array dimensi 1 & 2
Mampu membuat array dimensi 1 &
Membandingkan array 2

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
1
COLLECTIONS FRAMEWORK

A. TEORI
Platform Java mencakup kerangka koleksi. Collection adalah objek yang mewakili
sekelompok objek (seperti kelas Vektor klasik). Collections Framework adalah arsitektur
terpadu untuk merepresentasikan dan memanipulasi collections, sehingga collections
dapat dimanipulasi secara independen dari detail implementasi. Collections pada java
adalah framework yang menyediakan arsitektur untuk menyimpan dan memanipulasi
kelompok objek. Semua operasi yang dilakukan pada data seperti pencarian (searching),
sortasi (sorting), penyisipan (insertion), manipulasi (manipulation), penghapusan
(deletion), dan lain-lain dapat dilakukan oleh Java Collections. Collection adalah suatu
obyek yang bisa digunakan untuk menyimpan sekumpulan obyek. Obyek yang ada dalam
Collection disebut elemen. Collection menyimpan elemen yang bertipe Object, sehingga
berbagai tipe obyek bisa disimpan dalam Collection. Class-class mengenai Collection
tergabung dalam Java Collection Framework. Classclass Collection diletakkan dalam
package [Link] dan mempunyai dua interface utama yaitu Collection dan Map. Mulai
java 1.5 (juga dikenal sebagai J2SE 5), semua class yang termasuk Java Collection
Framework adalah class generics. Untuk kompatibilitas dengan versi java sebelumnya,
penggunaan generics tidak diharuskan, namun sangat disarankan. Kerangka Java
Collection menyediakan banyak antarmuka (Set, List, Queue, Deque dll.) Dan kelas
(ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet dll).
Keuntungan utama kerangka koleksi adalah:
Mengurangi upaya pemrograman dengan menyediakan struktur data dan algoritma
sehingga programmer tidak perlu menuliskannya sendiri.
Meningkatkan kinerja dengan memberikan penerapan struktur dan algoritma

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
2
data berkinerja tinggi. Karena berbagai implementasi, masing-masing antarmuka
dapat saling dipertukarkan, program dapat disesuaikan dengan implementasi
switching.
Menyediakan interoperabilitas antara API yang tidak terkait dengan membuat bahasa
umum untuk lulus koleksi bolak-balik.
Mengurangi upaya yang diperlukan untuk mempelajari API dengan meminta
programmer mempelajari beberapa collections API ad hoc.
Mengurangi upaya yang diperlukan untuk merancang dan menerapkan API dengan
tidak mengharuskan Anda menghasilkan API koleksi ad hoc.
Fosters software reuse dengan menyediakan antarmuka standar untuk collections dan
algoritma yang digunakan untuk memanipulasinya.
Kerangka Collections terdiri dari:
Antarmuka Collections (Collection Interface). Mewakili berbagai jenis koleksi,
seperti kumpulan, daftar, dan peta. Antarmuka ini membentuk dasar kerangka
kerja.
General-purpose implementations. Implementasi utama dari collectionsi.
Legacy implementations. Implementasi lawas Kelas koleksi dari rilis sebelumnya,
Vector dan Hashtable, dipasang untuk mengimplementasikan koleksi koleksi.
Special-purpose implementations. Implementasi dirancang untuk digunakan dalam
situasi khusus. Implementasi ini menampilkan karakteristik kinerja yang tidak
standar, pembatasan penggunaan, atau perilaku.
Concurrent implementations. Implementasi yang dirancang untuk penggunaan
secara bersamaan.
Wrapper implementations. Tambahkan fungsionalitas, seperti sinkronisasi, ke
implementasi lainnya.
Convenience implementations. Kinerja tinggi "implementasi mini" dari collections.

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
3
Abstract implementations. Implementasi parsial dari kumpulan collection untuk
memfasilitasi implementasi kustom.
Algorithms. Metode statis yang berguna untuk menjalankan fungsi pada collection,
seperti menyortir daftar.
Infrastructure. Antarmuka yang memberikan dukungan penting untuk collections.
Array Utilities. Fungsi utilitas untuk array tipe primitif dan objek referensi. Tidak,
secara tegas, bagian dari kerangka koleksi, fitur ini ditambahkan ke platform Java
bersamaan dengan kerangka koleksi dan bergantung pada beberapa infrastruktur
yang sama.
Hirarki Collection Framework
Hirarki Collections Framework dapat dilihat pada Gambar 2.1. Paket [Link] berisi
semua kelas (classes) dan antarmuka (interface) untuk Collections Framework.

Gambar 2.1 Hirarki Collection Framework


(sumber: [Link])

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
4
Methods pada Collections Interface

Metode pada Collections Interface dapat dilihat pada Tabel 2.1.

Tabel 2.1 Methods pada Collections Framework

No. Method Description

1 public boolean add(Object is used to insert an element in this collection.


element)

2 public boolean is used to insert the specified collection elements in the invoking
addAll(Collection c) collection.

3 public boolean remove(Object is used to delete an element from this collection.


element)

4 public boolean is used to delete all the elements of specified collection from the
removeAll(Collection c) invoking collection.

5 public boolean is used to delete all the elements of invoking collection except the
retainAll(Collection c) specified collection.

6 public int size() return the total number of elements in the collection.

7 public void clear() removes the total no of element from the collection.

8 public boolean contains(Object is used to search an element.


element)

9 public boolean is used to search the specified collection in this collection.


containsAll(Collection c)

10 public Iterator iterator() returns an iterator.

11 public Object[] toArray() converts collection into array.

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
5
No. Method Description

12 public boolean isEmpty() checks if collection is empty.

13 public boolean matches two collection.


equals(Object element)

14 public int hashCode() returns the hashcode number for collection.

Iterator Interface

Antarmuka Iterator menyediakan fasilitas untuk iterasi elemen ke arah depan saja.

Metode Iterator Interface

Hanya ada tiga metode di antarmuka Iterator. Metode Iterator Interface dapat dilihat pada
Tabel 2.2.

Tabel 2.2 Metode Iterator Interface


No. Method Description

1 public boolean hasNext() It returns true if iterator has more elements.

2 public Object next() It returns the element and moves the cursor pointer to the next element.

3 public void remove() It removes the last elements returned by the iterator. It is rarely used.

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
6
1. List
List digunakan untuk menyimpan sekumpulan obyek berdasarkan urutan masuk (ordered)
dan menerima duplikat. Cara penyimpanannya seperti array, oleh sebab itu memiliki
posisi awal dan posisi akhir, menyisipkan obyek pada posisi tertentu, mengakses dan
menghapus isi list, dimana semua proses ini selalu didasarkan pada urutannya.
Classclass yang mengimplementasikan interface List adalah Vector, Stack, Linked List
dan Array List. Terdapat interface Queue yang cara penyimpanan seperti List, interface ini
menyimpan obyek menggunakan metode FIFO (First In First Out) yaitu obyek yang
masuk pertama keluar pertama. Class- class yang mengimplementasikan interface Queue
adalah PriorityQueue dan LinkedList. Data yang tersimpan pada obyek PriorityQueue
akan diurutkan, data tersebut harus mengimplementasikan obyek Comparable atau
Comparator.
Array List
Kelas Java ArrayList menggunakan array dinamis (dinamic array) untuk menyimpan
elemen. Ini mewarisi kelas AbstractList dan mengimplementasikan antarmuka Daftar
(Implement List Interface).

Poin penting tentang kelas Java ArrayList adalah:

Kelas Java ArrayList bisa berisi elemen duplikat.

Kelas Java ArrayList mempertahankan urutan penyisipan.

Kelas Java ArrayList tidak sinkron.

Java ArrayList memungkinkan akses acak karena array bekerja berdasarkan indeks.

Di kelas Java ArrayList, manipulasi lambat karena banyak pergeseran yang terjadi
jika ada elemen yang dihapus dari daftar array.

ArrayList tidak dapat digunakan untuk tipe primitif, seperti int, char, dll

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
7
Hirarki kelas Java ArrayList

Hirarki kelas java ArrayList dapat dilihat pada Gambar 2.2.

Gambar 2.2 Hirarki Kelas ArrayList

Deklarasi kelas ArrayList

Mari kita lihat deklarasi untuk kelas [Link].

Array vs ArrayList in Java


Pada Java memiliki dua cara berbeda untuk membuat array, berikut contohnya:
1. Array: Array memiliki ukuran tetap dan sederhana

int arr[] = new int[10]

2. ArrayList : Ukuran Array dinamis yang mengimplementasikan antarmuka Daftar (List


Interface).

ArrayList<Type> arrL = new ArrayList<Type>();

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
8
Here Type is the type of elements in ArrayList to be created

Constructors pada ArrayList Java

Tabel 2.3 Constructors ArrayList

Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Colle It is used to build an array list that is initialized with the


ction c) elements of the collection c.

ArrayList(int It is used to build an array list that has the specified initial
capacity) capacity.

Methods ArrayList Java

Tabel 2.4 Methods ArrayList

Method Description

void add(int It is used to insert the specified element at the specified


index, Object position index in a list.
element)

boolean It is used to append all of the elements in the specified


addAll(Collectio collection to the end of this list, in the order that they are
n c) returned by the specified collection's iterator.

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
9
Method Description

void clear() It is used to remove all of the elements from this list.

int It is used to return the index in this list of the last occurrence
lastIndexOf(Obje of the specified element, or -1 if the list does not contain this
ct o) element.

Object[] It is used to return an array containing all of the elements in


toArray() this list in the correct order.

Object[] It is used to return an array containing all of the elements in


toArray(Object[] this list in the correct order.
a)

boolean It is used to append the specified element to the end of a list.


add(Object o)

boolean addAll(int It is used to insert all of the elements in the specified


index, Collection collection into this list, starting at the specified position.
c)

Object clone() It is used to return a shallow copy of an ArrayList.

int It is used to return the index in this list of the first occurrence
indexOf(Object of the specified element, or -1 if the List does not contain
o) this element.

void It is used to trim the capacity of this ArrayList instance to be


trimToSize() the list's current size.

Beberapa metode penting yang perlu dipelajari:

1) add( Object o): Metode ini menambahkan objek ke arraylist.

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
10
[Link]("assalamu’alaikum");
Pernyataan ini akan menambahkan string Assalamu’alaikum pada daftar array
pada posisi terakhir.

2) add(int index, Object o): Ini menambahkan objek ke daftar array pada indeks yang
diberikan.
[Link](2, "monggo");
Ini akan menambahkan string sampai ke indeks ke-2 (posisi ke-3 sebagai daftar
array dimulai dengan indeks 0) dari daftar array.

3) remove(Object o): Menghapus objek dari ArrayList.


[Link]("Ovide");
Pernyataan ini akan menghapus string "Ovide" dari ArrayList.

4) remove(int index): Menghapus elemen dari indeks tertentu.


[Link](3);
Ini akan menghapus elemen indeks 3 (elemen ke 4 dari daftar - List dimulai
dengan 0).

5) set(int index, Object o): Digunakan untuk mengupdate sebuah elemen. Ini
menggantikan elemen yang ada pada indeks yang ditentukan dengan objek o.
[Link](2, "Harfiah");
Ini akan menggantikan elemen ke-3 (index = 2 adalah elemen ke-3) dengan nilai
Harfiah.

6) int indexOf(Object o): Memberikan indeks objek o. Jika elemen tidak


ditemukan dalam daftar maka metode ini mengembalikan nilai -1.
int pos = [Link]("Harfiah");
Ini akan memberi indeks (posisi) dari string Harfiah dalam daftar.

7) Object get(int index): Ia mengembalikan objek daftar yang ada pada indeks
yang ditentukan.
String str= [Link](2);
Fungsi get akan mengembalikan string yang tersimpan pada posisi ke 3 (indeks 2)
dan akan diberikan ke string "str". Kami telah menyimpan nilai yang dikembalikan dalam
variabel string karena pada contoh kami, kami mendefinisikan ArrayList

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
11
adalah tipe String. Jika Anda memiliki daftar array integer maka nilai yang dikembalikan
harus disimpan dalam variabel bilangan bulat.

8) int size(): Ini memberi ukuran ArrayList - Jumlah elemen dari daftar. int

numberofitems = [Link]();
9) boolean contains(Object o): Ini memeriksa apakah objek yang diberikan ada
pada daftar array jika ada maka akan mengembalikan true jika yang lain (else) maka
mengembalikan (return) false.
[Link]("Ibrahim");
Ini akan kembali benar jika string "Ibrahim" ada dalam daftar, jika yang lain maka
akan salah.

10) clear(): Digunakan untuk menghapus semua elemen dari daftar array dalam sekali
jalan. Kode di bawah ini akan menghapus semua elemen ArrayList yang objeknya obj.
[Link]();
Cara menginisialisasi ArrayList

Berikut beberapa metode untuk menginisialisasi ArrayList:

Metode 1: Inisialisasi menggunakan [Link]

Syntax:

ArrayList<Type> obj = new ArrayList<Type>(


[Link](Object o1, Object o2, Object o3, ....so on));
Contoh:

import [Link].*;
public class InitializationExample1 { public
static void main(String args[]) {
ArrayList<String> obj = new ArrayList<String>( [Link]("Ovide",
"Harfiah", "Hury El ‘Ain"));
[Link]("Daftar Elements Nama:"+obj);
}
}

Keluaran:

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
12
Daftar Elements Nama:[Ovide, Harfiah, Hury El ‘Ain]

Metode 2: Metode kelas dalam anonim untuk menginisialisasi ArrayList

Syntax:

ArrayList<T> obj = new ArrayList<T>(){{


add(Object o1);
add(Object o2);
add(Object o3);
...
...
}};
Contoh:

import [Link].*;
public class InitializationExample2 { public
static void main(String args[]) {
ArrayList<String> namakota = new ArrayList<String>(){{ add("Jakarta");
add("Yogyakarta");
add("Surakarta");
}};
[Link]("Berisi Array list nama kota:"+namakota);
}
}

Keluaran:

Berisi Array list nama kota:[Jakarta, Yogyakarta, Surakarta]

Metode3: Cara normal inisialisasi ArrayList

Syntax:

ArrayList<T> obj = new ArrayList<T>();


[Link]("Object o1");
[Link]("Object o2");

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
13
[Link]("Object o3");
...
...
Contoh:

import [Link].*; public


class Details {
public static void main(String args[]) {
ArrayList<String> buku = new ArrayList<String>();
[Link]("Buku Java1");
[Link]("Buku Java2");
[Link]("Buku Java3");
[Link]("Daftar Buku dijual di array list adalah: "+buku);
}
}

Keluaran:

Daftar Buku dijual di array list adalah: [Buku Java1, Buku Java2, Buku Java3]

Method 4: Use [Link]

Metode [Link] dapat digunakan saat kita perlu menginisialisasi ArrayList


dengan nilai yang sama untuk semua elemennya. Syntax: count adalah jumlah elemen
dan elemen adalah nilai item
ArrayList<T> obj = new ArrayList<T>([Link](count, element));
Contoh:

import [Link].*; public


class Details {
public static void main(String args[]) { ArrayList<Integer>
intlist = new
ArrayList<Integer>([Link](10, 5));
[Link]("ArrayList items: "+intlist);
}
}

Keluaran:

ArrayList items: [5, 5, 5, 5, 5, 5, 5, 5, 5, 5]

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
14
Linked List
Kelas Java LinkedList menggunakan doubly Linked List terkait untuk menyimpan elemen.
Ini menyediakan struktur data linked-list. Ini mewarisi kelas AbstractList dan
mengimplementasikan daftar dan antarmuka Deque.
Poin penting tentang Java LinkedList adalah:
Kelas Java LinkedList dapat berisi elemen duplikat.
Kelas Java LinkedList mempertahankan urutan penyisipan.
Kelas Java LinkedList tidak sinkron.
Di kelas Java LinkedList, manipulasi cepat karena tidak ada pergeseran yang perlu
dilakukan.
Kelas Java LinkedList dapat digunakan sebagai list, stack atau queue.
Hirarki kelas LinkedList
Seperti ditunjukkan pada diagram Gambar 2.3., kelas Java LinkedList memperluas kelas
AbstractSequentialList dan mengimplementasikan daftar dan antarmuka Deque.

Gambar 2.3 Hirarki Linked List

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
15
Doubly Linked List
Dalam kasus doubly linked list, kita dapat menambahkan atau menghapus elemen dari
kedua sisi.

Gambar 2.4 Doubly Linked List

Deklarasi Kelas LinkedList

Deklarasi untuk kelas [Link]

public class LinkedList<E> extends AbstractSequentialList<E> implements List<E


>, Deque<E>, Cloneable, Serializable

Constructors LinkedList

Constructor Description

LinkedList() It is used to construct an empty list.

LinkedList(Collection c) It is used to construct a list containing the elements of the specified


collection, in the order they are returned by the collection's iterator.

Methods LinkedList

Method Description

void add(int index, It is used to insert the specified element at the specified position index
Object element) in a list.

void addFirst(Object o) It is used to insert the given element at the beginning of a list.

void addLast(Object o) It is used to append the given element to the end of a list.

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
16
Method Description

int size() It is used to return the number of elements in a list

boolean add(Object o) It is used to append the specified element to the end of a list.

boolean It is used to return true if the list contains a specified element.


contains(Object o)

boolean remove(Object o) It is used to remove the first occurence of the specified element in a
list.

Object getFirst() It is used to return the first element in a list.

Object getLast() It is used to return the last element in a list.

int indexOf(Object o) It is used to return the index in a list of the first occurrence of
the specified element, or -1 if the list does not contain any
element.

int lastIndexOf(Object It is used to return the index in a list of the last occurrence of the
o) specified element, or -1 if the list does not contain any element.

2. Set
Set mengikuti model himpunan, dimana obyek/anggota yang tersimpan dalam Set harus
unik. Urutan maupun letak dari anggota tidaklah penting, hanya keberadaan anggota
saja yang penting. Class-class yang mengimplementasikan interface Set adalah HashSet.
Interface SortedSet merupakan subInterface dari interface Set. Untuk mengurutkan Set,
kita dapat menggunakan class yang mengimplementasikan interface SortedSet yaitu clas
TreeSet.
HashSet
Kelas Java HashSet digunakan untuk membuat koleksi yang menggunakan tabel hash
untuk penyimpanan. Ini mewarisi kelas AbstractSet dan

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
17
mengimplementasikan antarmuka Set.
Poin penting tentang kelas Java HashSet adalah:
HashSet menyimpan elemen dengan menggunakan mekanisme yang disebut
hashing.
HashSet hanya berisi unsur unik saja.
Perbedaan antara List dan Set, List bisa berisi elemen duplikat sedangkan Set hanya
berisi elemen unik.
Hirarki kelas HashSet
Kelas HashSet memperluas kelas AbstractSet yang mengimplementasikan antarmuka
Set. Antarmuka Set mewarisi antarmuka Koleksi dan Iterabel dalam urutan hierarkis.

Gambar 2.5 Hirarki HashSet

Deklarasi Kelas HashSet

Declaration Kelas [Link]

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable,


S erializable

Constructors Kelas HashSet

Constructor Description

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
18
HashSet() It is used to construct a default HashSet.

HashSet(Collection It is used to initialize the hash set by using the elements of the collection
c) c.

HashSet(int It is used to initialize the capacity of the hash set to the given integer
capacity) value capacity. The capacity grows automatically as elements are
added to the HashSet.

Methods Kelas HashSet

Method Description

void clear() It is used to remove all of the elements from this set.

boolean It is used to return true if this set contains the specified element.
contains(Object o)

boolean It is used to adds the specified element to this set if it is not already
add(Object o) present.

boolean isEmpty() It is used to return true if this set contains no elements.

boolean It is used to remove the specified element from this set if it is present.
remove(Object o)

Object clone() It is used to return a shallow copy of this HashSet instance: the elements
themselves are not cloned.

Iterator iterator() It is used to return an iterator over the elements in this set.

int size() It is used to return the number of elements in this set.

TreeSet
Kelas Java TreeSet mengimplementasikan antarmuka Set yang menggunakan

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
19
pohon untuk penyimpanan. Ini mewarisi kelas AbstractSet dan mengimplementasikan
antarmuka NavigableSet. Objek kelas TreeSet disimpan dalam urutan menaik.
Poin penting tentang kelas Java TreeSet adalah:
Berisi elemen unik hanya seperti HashSet.
Waktu akses dan pengambilan cepat.
Pertahankan urutan naik.
Hirarki kelas TreeSet
Seperti ditunjukkan pada Gambar 2.6 , kelas Java TreeSet mengimplementasikan
antarmuka NavigableSet. Antarmuka NavigableSet memperluas SortedSet, Set,
Collection dan Iterable interface dalam urutan hirarkis.

Gambar 2.6 Hirarki TreeSet

Deklarasi TreeSet

Deklarasi Kelas [Link].

public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Clo


neable, Serializable

Constructors Kelas TreeSet

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
20
Constructor Description

TreeSet() It is used to construct an empty tree set that will be sorted in an


ascending order according to the natural order of the tree set.

TreeSet(Collection c) It is used to build a new tree set that contains the elements of the
collection c.

TreeSet(Comparator It is used to construct an empty tree set that will be sorted according
comp) to given comparator.

TreeSet(SortedSet ss) It is used to build a TreeSet that contains the elements of the given
SortedSet.

Methods of Java TreeSet class

Method Description

boolean It is used to add all of the elements in the specified collection to


addAll(Collection c) this set.

boolean It is used to return true if this set contains the specified element.
contains(Object o)

boolean isEmpty() It is used to return true if this set contains no elements.

boolean It is used to remove the specified element from this set if it is


remove(Object o) present.

void add(Object o) It is used to add the specified element to this set if it is not already
present.

void clear() It is used to remove all of the elements from this set.

Object clone() It is used to return a shallow copy of this TreeSet instance.

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
21
Object first() It is used to return the first (lowest) element currently in this sorted
set.

Object last() It is used to return the last (highest) element currently in this sorted
set.

int size() It is used to return the number of elements in this set.

3. Map
Perbedaaan mendasar map dengan collection yang lain, untuk menyimpan obyek pada
Map, perlu sepasang obyek, yaitu key yang bersifat unik dan nilai yang disimpan. Untuk
mengakses nilai tersebut maka kita perlu mengetahui key dari nilai tersebut. Map juga
dikenal sebagai dictionary/kamus. Pada saat menggunakan kamus, perlu suatu kata yang
digunakan untuk pencarian. Class-class yang mengimplementasikan Map adalah
Hashtable,HashMap, LinkedHashMap. Untuk mengurutkan Map menggunakan interface
SortedMap, class yang mengimplementasikan interface tersebut adalah TreeMap.
HashMap
Kelas Java HashMap mengimplementasikan antarmuka peta dengan menggunakan
hashtable. Ini mewarisi kelas AbstractMap dan mengimplementasikan antarmuka Peta.
Poin penting tentang kelas Java HashMap adalah:
HashMap berisi nilai berdasarkan kunci.
hanya berisi unsur unik.
Bisa memiliki satu kunci nol dan beberapa nilai null.
Tidak mengatur pesanan.
Hirarki kelas HashMap
Seperti ditunjukkan pada Gambar 2.8, kelas HashMap memperluas kelas
AbstractMap dan mengimplementasikan antarmuka Peta.

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
22
Gambar 2.8 Hirarki HashMap

Deklarasi Kelas HashMap

Deklarasi Kelas [Link]

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cl oneable,


Serializable

Parameter Kelas HashMap

Parameters Kelas [Link]

o K: It is the type of keys maintained by this map.


o V: It is the type of mapped values.

Constructors Kelas HashMap

Constructor Description

HashMap() It is used to construct a default HashMap.

HashMap(Map m) It is used to initializes the hash map by using the elements of the given
Map object m.

HashMap(int capacity) It is used to initializes the capacity of the hash map to the given integer
value, capacity.

HashMap(int capacity, It is used to initialize both the capacity and fill ratio of the hash map by
float fillRatio) using its arguments.

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
23
Methods Kelas HashMap

Method Description

void clear() It is used to remove all of the mappings from this map.

boolean It is used to return true if this map contains a mapping for the specified
containsKey(Object key) key.

boolean It is used to return true if this map maps one or more keys to the specified
containsValue(Object value.
value)

boolean isEmpty() It is used to return true if this map contains no key-value mappings.

Object clone() It is used to return a shallow copy of this HashMap instance: the keys
and values themselves are not cloned.

Set entrySet() It is used to return a collection view of the mappings contained in this
map.

Set keySet() It is used to return a set view of the keys contained in this map.

Object put(Object key, It is used to associate the specified value with the specified key in this
Object value) map.

int size() It is used to return the number of key-value mappings in this map.

Collection values() It is used to return a collection view of the values contained in this map.

Linked HashMap

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
24
Kelas Java LinkedHashMap adalah tabel Hash dan implementasi daftar Linked dari
antarmuka Peta, dengan urutan iterasi yang dapat diprediksi. Ini mewarisi kelas HashMap
dan mengimplementasikan antarmuka Peta.
Poin penting tentang kelas Java LinkedHashMap adalah:
LinkedHashMap berisi nilai berdasarkan kunci.
hanya berisi unsur unik.
mungkin memiliki satu kunci nol dan beberapa nilai null.
Sama seperti HashMap dapat mengatur penyisipan.

Deklarasi Kelas LinkedHashMap

Deklarasi Kelas [Link]

public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>

Parameters Kelas LinkedHashMap

Parameters Kelas [Link].

o K: It is the type of keys maintained by this map.


o V: It is the type of mapped values.

Constructors Kelas LinkedHashMap

Constructor Description

LinkedHashMap() It is used to construct a default LinkedHashMap.

LinkedHashMap(int It is used to initialize a LinkedHashMap with the given capacity.


capacity)

LinkedHashMap(int It is used to initialize both the capacity and the fillRatio.


capacity, float fillRatio)

LinkedHashMap(Map m) It is used to initialize the LinkedHashMap elements with the


from the given Map class m.

Methods Kelas LinkedHashMap

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
25
Method Description

Object get(Object key) It is used to return the value to which this map maps the
specified key.

void clear() It is used to remove all mappings from this map.

boolean It is used to return true if this map maps one or more keys to the
containsKey(Object key) specified value.

TreeMap
Kelas Java TreeMap mengimplementasikan antarmuka Peta dengan menggunakan
pohon. Ini menyediakan sarana yang efisien untuk menyimpan pasangan kunci / nilai
dalam urutan yang diurutkan.
Poin penting tentang kelas Java TreeMap adalah:
TreeMap berisi nilai berdasarkan kunci. Ini mengimplementasikan antarmuka
NavigableMap dan memperluas kelas AbstractMap.
hanya berisi unsur unik.
tidak dapat memiliki kunci null tetapi dapat memiliki beberapa nilai null.
Sama seperti HashMap malah mempertahankan tatanan naik (ascending order).

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
26
Gambar 2.9 Hirarki TreeMap

TreeMap class declaration

Deklarasi [Link] class.

public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMa


p<K,V>, Cloneable, Serializable

Parameters TreeMap class

Parameters for [Link] class.

o K: It is the type of keys maintained by this map.


o V: It is the type of mapped values.

Constructors TreeMap class


Constructor Description

TreeMap() It is used to construct an empty tree map that will be sorted using the
natural order of its key.

TreeMap(Comparator It is used to construct an empty tree-based map that will be sorted using
comp) the comparator comp.

TreeMap(Map m) It is used to initialize a tree map with the entries from m, which will be
sorted using the natural order of the keys.

TreeMap(SortedMap It is used to initialize a tree map with the entries from the SortedMap
sm) sm, which will be sorted in the same order as sm.

Methods TreeMap class

Method Description

boolean containsKey(Object It is used to return true if this map contains a mapping for the
key) specified key.

boolean It is used to return true if this map maps one or more keys to

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
27
containsValue(Object value) the specified value.

Object firstKey() It is used to return the first (lowest) key currently in this sorted
map.

Object get(Object key) It is used to return the value to which this map maps the specified
key.

Object lastKey() It is used to return the last (highest) key currently in this sorted
map.

Object remove(Object key) It is used to remove the mapping for this key from this TreeMap if
present.

void putAll(Map map) It is used to copy all of the mappings from the specified map to this
map.

Set entrySet() It is used to return a set view of the mappings contained in this
map.

int size() It is used to return the number of key-value mappings in this map.

Collection values() It is used to return a collection view of the values contained in this
map.

B. PERCOBAAN
Percobaan 1 : Menggunakan ArrayList
package praktikum2;
import [Link].*;
/**
*
* @author ovide
*/
public class ArrayListCollection {

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
28
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
ArrayList<String> list=new ArrayList<>();//Creating arraylist
[Link]("Hury El 'Ain");//Adding object in arraylist
[Link]("Haniifa Yui");
[Link]("Hazema");
[Link]("Hanif Ibrahim");
//Traversing list through Iterator
Iterator itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}

Percobaan 2 : ArrayList
package praktikum2;
import [Link].*;

/**
*
* @author ovide
*/
public class ArrayList1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// size of ArrayList
int n = 5;

//declaring ArrayList with initial size n


ArrayList<Integer> arrli = new ArrayList<>(n);

// Appending the new element at the end of the list

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
29
for (int i=1; i<=n; i++)
[Link](i);

// Printing elements
[Link](arrli);

// Remove element at index 3


[Link](3);

// Displaying ArrayList after deletion


[Link](arrli);

// Printing elements one by one


for (int i=0; i<[Link](); i++)
[Link]([Link](i)+" ");
}
}

Praktikum 3 : Memahami penggunaan class list yang mengimplementasikan interface List


yaitu ArrayLis dan Linked List
package praktikum2;
import [Link].*;
/**
*
* @author ovide
*/
public class ListExample {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
List list=new ArrayList(); [Link]("Ovide");
[Link]("Djiman");
[Link]("Rise");

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
30
[Link]("Yanuar");
[Link]("Hanif");
[Link](list);
[Link]("2 : "+[Link](2));
[Link]("0 : "+[Link](0));
LinkedList queue=new LinkedList();
[Link]("Ovide");
[Link]("Djiman");
[Link]("Rise");
[Link]("Yanuar");
[Link]("Hanif");
[Link](queue);
[Link]();
[Link]();
[Link](queue);
}
}

Praktikum 4 : Vektor
package praktikum2;
import [Link].*; import
[Link].*;
/**
*
* @author ovide
*/
public class VectorExample {

public static void main(String[] args) {


// creating an ArrayList
ArrayList<String> al = new ArrayList<>();

// adding object to arraylist


[Link]("[Link]");

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
31
[Link]("[Link]");
[Link]("[Link]");
[Link]("[Link]");

// traversing elements using Iterator'


[Link]("ArrayList elements are:");
Iterator it = [Link]();
while ([Link]())
[Link]([Link]());

// creating Vector
Vector<String> v = new Vector<>();
[Link]("Practice");
[Link]("quiz");
[Link]("code");

// traversing elements using Enumeration


[Link]("\nVector elements are:");
Enumeration e = [Link]();
while ([Link]())
[Link]([Link]());
}
}

Praktikum 5 : HashSet
package praktikum2;

import [Link];
import [Link];

/**
*
* @author ovide

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
32
*/
public class TestHashSet {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
HashSet<String> h = new HashSet<>();

// adding into HashSet


[Link]("India");
[Link]("Australia");
[Link]("South Africa");
[Link]("India");// adding duplicate elements

// printing HashSet
[Link](h);
[Link]("List contains India or not:" +
[Link]("India"));

// Removing an item
[Link]("Australia");
[Link]("List after removing Australia:"+h);

// Iterating over hash set items


[Link]("Iterating over list:");
Iterator<String> i = [Link]();
while ([Link]())
[Link]([Link]());
}
}

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
33
Praktikum 6 : LinkedHashSet
package praktikum2;
import [Link];
/**
*
* @author ovide
*/
public class LinkedHashSetExample {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// LinkedHashSet of String Type
LinkedHashSet<String> lhset = new LinkedHashSet<>();

// Adding elements to the LinkedHashSet


[Link]("Z");
[Link]("PQ");
[Link]("N");
[Link]("O");
[Link]("KK");
[Link]("FGH");
[Link](lhset);

// LinkedHashSet of Integer Type


LinkedHashSet<Integer> lhset2 = new LinkedHashSet<>();

// Adding elements
[Link](99);
[Link](7);
[Link](0);
[Link](67);

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
34
[Link](89);
[Link](66);
[Link](lhset2);
}
}

Praktikum 7 : TreeSet
package praktikum2;
import [Link];
/**
*
* @author ovide
*/
public class TreeSetExample {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// TreeSet of String Type TreeSet<String>
tset = new TreeSet<>();

// Adding elements to TreeSet<String>


[Link]("ABC");
[Link]("String");
[Link]("Test");
[Link]("Pen");
[Link]("Ink");
[Link]("Jack");

//Displaying TreeSet
[Link](tset);

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
35
// TreeSet of Integer Type TreeSet<Integer>
tset2 = new TreeSet<>();

// Adding elements to TreeSet<Integer>


[Link](88);
[Link](7);
[Link](101);
[Link](0);
[Link](3);
[Link](222);
[Link](tset2);
}
}

Praktikum 8 : HashMap
package praktikum2; import
[Link]; import
[Link]; import
[Link]; import
[Link];

/**
*
* @author ovide
*/
public class Details {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {

/* This is how to declare HashMap */ HashMap<Integer,


String> hmap = new HashMap<>();

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
36
/*Adding elements to HashMap*/
[Link](12, "Chaitanya");
[Link](2, "Rahul");
[Link](7, "Singh");
[Link](49, "Ajeet");
[Link](3, "Anuj");

/* Display content using Iterator*/


Set set = [Link]();
Iterator iterator = [Link]();
while([Link]()) {
[Link] mentry = ([Link])[Link]();
[Link]("key is: "+ [Link]() + " & Value is: ");
[Link]([Link]());
}

/* Get values based on key*/


String var= [Link](2);
[Link]("Value at index 2 is: "+var);

/* Remove values based on key*/


[Link](3);
[Link]("Map key and values after removal:"); Set
set2 = [Link]();
Iterator iterator2 = [Link]();
while([Link]()) {
[Link] mentry2 = ([Link])[Link]();
[Link]("Key is: "+[Link]() + " & Value is: ");
[Link]([Link]());
}

}
}

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
37
Praktikum 9 : LinkedHashMap
package praktikum2;
import [Link];
import [Link];
import [Link];
import [Link];
/**
*
* @author ovide
*/
public class LinkedHashMapDemo {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// HashMap Declaration
LinkedHashMap<Integer, String>
lhmap = new LinkedHashMap<>();

//Adding elements to LinkedHashMap


[Link](22, "Abey");
[Link](33, "Dawn");
[Link](1, "Sherry");
[Link](2, "Karon");
[Link](100, "Jim");

// Generating a Set of entries


Set set = [Link]();

// Displaying elements of LinkedHashMap


Iterator iterator = [Link]();
while([Link]()) {

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
38
[Link] me = ([Link])[Link]();
[Link]("Key is: "+ [Link]() +
"& Value is: "+[Link]()+"\n");
}
}
}

Praktikum 10 : TreeMap
package praktikum2;
import [Link];
import [Link]; import
[Link]; import
[Link];

/**
*
* @author ovide
*/
public class Details1 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
/* This is how to declare TreeMap */ TreeMap<Integer,
String>
tmap = new TreeMap<>();

/*Adding elements to TreeMap*/


[Link](1, "Data1");
[Link](23, "Data2");
[Link](70, "Data3");
[Link](4, "Data4");
[Link](2, "Data5");

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
39
/* Display content using Iterator*/
Set set = [Link]();
Iterator iterator = [Link]();
while([Link]()) {
[Link] mentry = ([Link])[Link]();
[Link]("key is: "+ [Link]() + " & Value is: ");
[Link]([Link]());
}

}
}

C. TUGAS
Tugas 1 : Penerapan konsep himpunan pada interface Set Terdapat sebuah himpunan
A = {1,2,3,4,5}
B = {5,6,7,8,9,10}
Menggunakan class yang mengimplementasikan Interface Set, dapatkah output seperti :
–A – B
–A ∩ B
–A U B
–A C B
Tugas 2 : Memahami penggunaan interface List.
Buatlah obyek List, dengan data bertipe String lakukan langkah berikut :
• Tampilkan data yang terdapat pada list.
• Baliklah data yang terdapat pada list dan tampilkan.
• Acaklah data tersebut dan tampilkan.
• Urutkan data tersebut dan tampilkan.

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
40
Tugas 3 : Penggunaan class LinkedList pada interface List.
Buatlah dua obyek List (ArrayList) yaitu obyek warna dan warnaDihapus. Obyek ini berisi
warna-warna, buatlah sebagian ada yang sama. Lakukan penghapusan data yang
terdapat pada obyek warna yang sama dengan data warna yang terdapat pada obyek
warna Dihapus, selanjutnya tampilkan.
Warna :
[MAGENTA, RED, WHITE, BLUE, CYAN]
Warna yang dihapus :
[RED, WHITE, BLUE]
Output :
Warna :
[MAGENTA, CYAN]

Tugas 4 : Pengurutan data mahasiswa berdasarkan nilai. Buatlah


class Mahasiswa dengan informasi :
• Nrp (String)
• Nama(String)
• Nilai(Float)
Terdapat 10 data mahasiswa yang tersimpan dalam queue, set nilai secara random
antara 60-100. Tampilkan data mahasiswa tersebut !
Tugas 5 : Mengetahui penggunaan class TreeMap
Inputkan kalimat, buatlah sebagian kata-kata dalam kalimat tersebut ada yang sama,
output berupa kata (sebagai key) dan jumlah kata (value) dalam kalimat tersebut yang
tersimpan dalam TreeMap, selanjutnya tampilkan.
Input : televisi kursi televisi kursi meja televisi monitor.
Output : kursi = 2 meja = 1 monitor = 1 televisi = 3

Tugas 6 : Mengetahui penggunaan class TreeMap


Melanjutkan latihan 5, tampilkan :
Tampilkan nilai terendah dan tertinggi

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
41
Output :
Nilai terendah : Meja = 1
Nilai tertinggi : Televisi = 3

Tampilkan berdasarkan key dengan awalan m.


Output :
meja = 1 monitor = 1

Tugas 7 : Ibukota propinsi di Indonesia


Terdapat objek TreeMap 1 yang berisi pulau (sebagai key) beserta
propinsipropinsinya(value). Terdapat objek TreeMap 2 yang berisi propinsi(sebagai key)
beserta ibukotanya(value). Tampilkan :
• Ibukota propinsi yang terdapat di pulau Sumatera
• Ibukota propinsi yang terdapat di pulau Jawa
• Ibukota propinsi yang berawalan S (Sumatera Utara, Sumatera Barat, Sumatera
Selatan, Sulawesi Barat, Sulawesi Tengah, Sulawesi Utara, Sulawesi Tenggara, Sulawesi
Selatan)
D. LAPORAN RESMI
Buatlah laporan resmi dari hasil (B) Percobaan & (C) Tugas berserta analisanya. Format
laporan sesuai dengan panduan.

2018 | Struktur Data Pemrograman Java | Modul 1


Ovide Decroly Wisnu Ardhi, S.T., [Link]
42

Anda mungkin juga menyukai