• Tidak ada hasil yang ditemukan

MODUL PRAKTIKUM STRUKTUR DATA DAN ALGORITMA GENERIC DAN IMPLEMENTASI COMPARETO()

N/A
N/A
Protected

Academic year: 2021

Membagikan "MODUL PRAKTIKUM STRUKTUR DATA DAN ALGORITMA GENERIC DAN IMPLEMENTASI COMPARETO()"

Copied!
11
0
0

Teks penuh

(1)

Viska Mutiawani, M.IT, Irvanizam, M.Sc, Dr. Taufik Fuadi Abidin Jurusan Informatika Universitas Syiah Kuala

MODUL PRAKTIKUM STRUKTUR DATA DAN ALGORITMA GENERIC DAN IMPLEMENTASI COMPARETO() Deskripsi Singkat

Praktikum 1 dan 2 yang telah anda lakukan melibatkan tipe data primitif. Contohnya class ArrayTakTerurut yang menyimpan data bertipe double. Sehingga jika ingin menyimpan tipe data lain, berarti kita harus membuat class Array yang lain lagi. Padahal di dalam Java, selain delapan tipe data primitif, juga terdapat tipe data berupa object. Oleh karena itu class yang bersifat collections (koleksi) diharapkan dapat digunakan untuk menyimpan berbagai macam tipe data. Sehingga collections tersebut dapat menggunakan super class nenek moyang yaitu Object. Namun penggunaan Object sendiri menjadikan data yang disimpan menjadi sangat bebas/flexible. Sehingga saat mengakses datanya akan memerlukan operasi casting. Generic dapat menyelesaikan masalah tersebut sebab generic menyediakan abstraksi pada tipe data. Bermakna tipe data yang dibuat generic sehingga dapat menerima tipe data apapun, namun pada satu waktu hanya satu jenis tipe data saja yang dapat digunakan.

Tujuan

1. Membuat class collection yang generic

2. Menggunakan method compareTo() pada interface Comparable

3. Memanfaatkan method compareTo() pada algoritma searching dan sorting

Materi 1 : Membuat Class Collection Biasa dan yang Generic

Class yang bersifat collection atau koleksi bermakna dapat digunakan untuk menyimpan data. Agar data yang disimpan bisa bermacam-macam maka digunakanlah data bertipe Object. Berikut kode programnya yang juga menyertakan method main yang mengecek class Store tersebut.

public class Store {

// instance variables - replace the example below with your own private Object value; // data

public Store () { value = null; }

public Object getValue() { return value; }

// set v as the new stored value public void setValue(Object v) { value = v; }

(2)

Viska Mutiawani, M.IT, Irvanizam, M.Sc, Dr. Taufik Fuadi Abidin Jurusan Informatika Universitas Syiah Kuala

public String toString()

{ return "value = " + value; }

public static void main(String []ar) {

Store s1 = new Store(); s1.setValue("hello");

String msg1 = (String) s1.getValue(); Store s2 = new Store();

s2.setValue( new Integer(5) );

Integer t2 = (Integer) s2.getValue();

String msg2 = s2.getValue(); //?

Integer t1 = (Integer) s1.getValue(); }

}

Apakah error yang muncul? Mengapa error tersebut bisa muncul?

Class Object memang dapat menampung semua class dalam Java. Namun tetap saja memprosesnya perlu menggunakan casting. Sehingga jika salah casting akan menimbulkan error compiler dan runtime (exception).

Untuk menyelesaikan masalah tersebut, kita akan menggunakan collection yang generic. Generic ditandakan dengan simbol yang dibatasi oleh kurung siku (contoh <T>). Class generic jika digunakan haruslah dikhususkan untuk tipe data tertentu sehingga tidak perlu proses casting untuk mengakses unsur collection. Berikut contoh class Store yang telah diubah menjadi generic.

public class StoreGeneric <T> {

// instance variables - replace the example below with your own private T value; // data of type/class T

public StoreGeneric () { value = null; }

// return the stored value as type T public T getValue()

{ return value; }

// update the stored value public void setValue(T v) { value = v; }

public String toString()

{ return "Value = " + value; }

(3)

Viska Mutiawani, M.IT, Irvanizam, M.Sc, Dr. Taufik Fuadi Abidin Jurusan Informatika Universitas Syiah Kuala

{

StoreGeneric<String> ss = new StoreGeneric<String>(); ss.setValue("hello");

String msg = ss.getValue();

StoreGeneric<Integer> st = new StoreGeneric<Integer>(); st.setValue( new Integer(10) );

Integer t = st.getValue();

String msg2 = ss.getValue(); // akan menghasilkan warning compiler //Integer t1 = ss.getValue();

} }

Beberapa tipe parameter yang umum digunakan pada generic:

 T - Type

 E - Element

 K - Key

 N - Number

 V - Value

Class StoreGeneric sama seperti class Store yaitu dapat menyimpan tipe data apapun. Namun class StoreGeneric saat digunakan haruslah dikhususkan untuk tipe data tertentu. Seperti objek ss yang telah dikhususkan hanya untuk menyimpan data String. Sedangkan objek st telah dikhususkan untuk menyimpan data Integer. Dengan menggunakan generic maka kita tidak perlu lagi melakukan casting.

Pada kode program di atas, coba hilangkan simbol komen pada Integer t1 = ss.getValue();

Compile kembali lalu perhatikant warning/error yang muncul. Mengapa muncul warning compiler?

Materi 2 : Interface yang Generic

Selain class, method dan interface juga dapat dibuat generic. Method yang generic telah anda gunakan secara tidak langsung pada class StoreGeneric. Membuat interface generic juga tidak terlalu jauh berbeda dengan class generic yaitu menggunakan simbol <>.

Berikut kode interface Accumulator yang dibuat generic.

public interface Accumulator<T> {

public void add(T v); }

(4)

Viska Mutiawani, M.IT, Irvanizam, M.Sc, Dr. Taufik Fuadi Abidin Jurusan Informatika Universitas Syiah Kuala

Interface Accumulator di atas akan diimplementasikan pada class berikut ini.

public class AccumulatorNumber implements Accumulator<Number> {

private double total; public AccumulatorNumber () { total = 0.0; }

public double getTotal() { return total; }

// add v to total as a double public void add(Number v)

{ total = total + v.doubleValue(); } }

Kemudian kita buat class untuk menguji interface Accumulator di atas. Kode programnya di bawah.

public class UsingAccumulator {

public static void main(String []ar) {

Integer[] intArr = {7, 1, 9, 3, 8, 4};

AccumulatorNumber accNumber = new AccumulatorNumber();

for (int i = 0; i < intArr.length; i++) accNumber.add(intArr[i]);

System.out.println("Numeric total is " +accNumber.getTotal()); }

}

Materi 3 : Method compareTo() di dalam Interface Comparable

Algoritma searching dan sorting yang telah kita buat pada praktikum 1 dan 2 dikhususkan untuk tipe data primitif. Jika kita ingin membandingkan tipe data berupa class tertentu, apalagi jika menggunakan generic, maka kita perlu cara yang khusus. Salah satu cara yang dapat digunakan adalah dengan menggunakan method compareTo() yang ada di dalam interface Comparable. Interface Comparable ada dalam Java API dan merupakan cara standar untuk membandingkan object. Method compareTo() akan mengembalikan nilai negatif, 0 dan positif.

 obj.compareTo(item) < 0 ketika obj < item

 obj.compareTo(item) == 0 ketika obj == item

 obj.compareTo(item) > 0 ketika obj > item Berikut contoh kode programnya.

(5)

Viska Mutiawani, M.IT, Irvanizam, M.Sc, Dr. Taufik Fuadi Abidin Jurusan Informatika Universitas Syiah Kuala

public class Employee implements Comparable<Employee> {

protected String empName; protected String empSSN;

public Employee(String empName, String empSSN) { this.empName = empName;

this.empSSN = empSSN; }

public void setName(String empName) { this.empName = empName; }

public String toString()

{ return "Name: " + empName + '\n' + "SS#: " + empSSN; } public String payrollCheck()

{ return ""; }

public int compareTo(Employee obj)

{ return empSSN.compareTo(obj.empSSN); } }

Kemudian kita buat class SalaryEmployee yang merupakan turunan dari class Employee.

import java.text.DecimalFormat;

// salaried employee "is an" employee with a fixed weekly salary public class SalaryEmployee extends Employee

{

// new attributes that extends attributes in Employee private double salary;

public SalaryEmployee(String empName, String empSSN, double salary)

{

// call the Employee superclass constructor super(empName, empSSN);

this.salary = salary; }

// accessor method to return the salary public double getSalary()

{ return salary; }

// mutator method to update the salary public void setSalary(double sal) { salary = sal; }

(6)

Viska Mutiawani, M.IT, Irvanizam, M.Sc, Dr. Taufik Fuadi Abidin Jurusan Informatika Universitas Syiah Kuala

// including name, ssn, status (salaried) and monthly pay public String toString()

{

DecimalFormat fmt = new DecimalFormat("#.00"); return super.toString() + '\n' +

"Status: Salary" + '\n' +

"Salary: $" + fmt.format(salary); }

// cut a payroll check with the employee name, social security // number in parentheses, and salary

public String payrollCheck() {

DecimalFormat fmt = new DecimalFormat("#.00"); return "Pay " + empName + " (" + empSSN + ") $" +

fmt.format(salary); }

}

Materi 4 : Penggunaan Method compareTo() pada Algoritma Searching dan Sorting

Class Arrays berikut ini merupakan versi collection yang memanfaatkan generic dan interface Comparable yang memiliki method compareTo().

public class Arrays {

// assure that the programmer cannot instantiate // an Arrays object

private Arrays() {}

/**

* Sorts an array of integer values in ascending order using the * selection sort algorithm.<p>

*

* This algorithm has O(n*n) runtime efficiency for best, worst, * and average case.

*

* @param arr the array to be sorted. */

public static void selectionSort(int[] arr) {

int smallIndex; // index of smallest element in the sublist int pass, j, n = arr.length;

int temp;

// pass has the range 0 to n-2 for (pass = 0; pass < n-1; pass++) {

(7)

Viska Mutiawani, M.IT, Irvanizam, M.Sc, Dr. Taufik Fuadi Abidin Jurusan Informatika Universitas Syiah Kuala

// scan the sublist starting at index pass smallIndex = pass;

// j traverses the sublist arr[pass+1] to arr[n-1] for (j = pass+1; j < n; j++)

// if smaller element found, assign smallIndex // to that position

if (arr[j] < arr[smallIndex]) smallIndex = j;

// swap the next smallest element into arr[pass] temp = arr[pass]; arr[pass] = arr[smallIndex]; arr[smallIndex] = temp; } } /**

* A generic version of the selection sort algorithm that orders an * array of elements of type T in ascending order. The

* algorithm requires that the generic type implements the * Comparable interface.

* This algorithm has O(n*n) runtime efficiency for best, worst, * and average case.

*

* @param arr the array to be sorted. */

public static <T extends Comparable<? super T>> void selectionSort(T[] arr)

{

int smallIndex; // index of smallest element in the sublist int pass, j, n = arr.length;

T temp;

// pass has the range 0 to n-2 for (pass = 0; pass < n-1; pass++) {

// scan the sublist starting at index pass smallIndex = pass;

// j traverses the sublist arr[pass+1] to arr[n-1] for (j = pass+1; j < n; j++)

// if smaller element found, assign smallIndex // to that position

if (arr[j].compareTo(arr[smallIndex]) < 0) smallIndex = j;

// swap the next smallest element into arr[pass] temp = arr[pass];

arr[pass] = arr[smallIndex]; arr[smallIndex] = temp; }

(8)

Viska Mutiawani, M.IT, Irvanizam, M.Sc, Dr. Taufik Fuadi Abidin Jurusan Informatika Universitas Syiah Kuala

} /**

* Searches the sublist [first, last) in an integer array for the * specified target value using the sequential search algorithm; * the return value is the first occurrence of a match or -1 if * not match is found.

*

* @param arr the integer array to be searched. * @param first starting index for the sublist. * @param last upper bound for the sublist.

* @param target the search key to locate in the sublist. *

* @return index of the search key, if it is contained in the * list; otherwise, -1.

*/

public static int seqSearch(int[] arr, int first, int last, int target)

{

// scan indices in the range first <= i < last; // return the index

// indicating the position if a match occurs; // otherwise return -1

for (int i = first; i < last; i++) if (arr[i] == target)

return i;

// no return yet if match is not found; return -1 return -1; // i = last, thus no match

} /**

* Searches the sublist [first, last) in a specified array of * objects for the specified target value using the sequential * search algorithm; comparison is made using the

* equals() method; the return value is

* the first occurrence of a match or -1 if not match is found. *

* @param arr the array to be searched.

* @param first starting index for the sublist. * @param last upper bound for the sublist.

* @param target the search key to locate in the sublist. *

* @return index of the search key, if it is contained in the * list; otherwise, -1.

*/

public static

int seqSearch(Object[] arr, int first, int last, Object target) {

// scan indices in the range first <= i < last; // return the index

(9)

Viska Mutiawani, M.IT, Irvanizam, M.Sc, Dr. Taufik Fuadi Abidin Jurusan Informatika Universitas Syiah Kuala

// otherwise return -1

for (int i = first; i < last; i++) if (arr[i].equals(target))

return i;

// no return yet if match is not found; return -1 return -1; // i = last, thus no match

} /**

* Searches an integer array for the specified target value using * the binary search algorithm. The array must be sorted into * ascending order.

*

* @param arr the integer array to be searched. * @param first starting index for the sublist. * @param last upper bound for the sublist.

* @param target the search key to locate in the sublist. *

* @return index of the search key, if it is contained in the * list;otherwise, -1.

*/

public static int binSearch(

int[] arr, int first, int last, int target) {

int mid; // index of the midpoint

int midValue; // object that is assigned arr[mid] int origLast = last; // save original value of last while (first < last) // test for nonempty sublist {

mid = (first+last)/2; midValue = arr[mid]; if (target == midValue)

return mid; // have a match // determine which sublist to search else if (target < midValue)

last = mid; // search lower sublist. reset last else

first = mid+1; //search upper sublist.reset first }

return -1; // target not found }

/**

* Searches the sublist [first, last) in a specified array of * objects for the specified target value using the binary search * algorithm; the generic type T must implement the

(10)

Viska Mutiawani, M.IT, Irvanizam, M.Sc, Dr. Taufik Fuadi Abidin Jurusan Informatika Universitas Syiah Kuala

* ascending order; comparison is made using the <tt>equals()</tt> * method; the return value is the first occurrence of a match or * -1 if not match is found. search algorithm.

*

* @param arr the integer array to be searched. * @param first starting index for the sublist. * @param last upper bound for the sublist.

* @param target the search key to locate in the sublist. *

* @return index of the search key, if it is contained in the * list; otherwise, -1.

*/

public static <T extends Comparable<? super T>>

int binSearch(T[] arr, int first, int last, T target) {

int mid; // index of the midpoint

T midvalue; // object that is assigned arr[mid] int origLast = last; // save original value of last while (first < last) // test for nonempty sublist {

mid = (first+last)/2; midvalue = arr[mid];

if (target.compareTo(midvalue) == 0) return mid; // have a match // determine which sublist to search else if (target.compareTo(midvalue) < 0)

last = mid; // search lower sublist. reset last else

first = mid+1; // search upper sublist. reset first }

return -1; // target not found }

/**

* Returns a string that displays the elements in the array in * sequential order. The description is a comma separated list of * elements enclosed in brackets.

* @return string that contains the list of elements in the array. */

// returns a string that represents an array of objects public static String toString(Object[] arr)

{

if (arr == null) return "null";

else if (arr.length == 0) return "[]";

// start with the left bracket String str = "[" + arr[0];

(11)

Viska Mutiawani, M.IT, Irvanizam, M.Sc, Dr. Taufik Fuadi Abidin Jurusan Informatika Universitas Syiah Kuala

// append all but the last element, separating items with a comma // polymorphism calls toString() for the array type

for (int i = 1; i < arr.length; i++) str += ", " + arr[i];

str += "]"; return str; }

}

Berikutnya kita buat class GenericSorting yang akan mengurutkan data apa saja yang ingin diurutkan, asalkan class data tersebut telah meng-implement Comparable dan override method compareTo().

public class GenericSorting {

public static void main(String []ar) {

Integer[] intArr = {40, 70, 50, 30}; SalaryEmployee[] emp = {

new SalaryEmployee("Dunn, Moira","471-23-8092",800), new SalaryEmployee("Garcia, Avey", "398-67-1298",1200), new SalaryEmployee("Ye, Don", "682-76-1298",2000)}; Arrays.selectionSort(intArr);

System.out.println("Sorted integers: " +Arrays.toString(intArr));

Arrays.selectionSort(emp);

for (int i=0; i < emp.length; i++)

System.out.println(emp[i].payrollCheck()); }

}

LATIHAN 1

Buat semua class-class yang ada dalam praktikum ini. Apakah yang dapat anda simpulkan?

SOAL-SOAL 1.

Referensi

Dokumen terkait

Disimpulkan dari hasil analisis sekuens nukleotida gen dan asam amino protein H ditemukan perbedaan sekuens asam amino epitop sel T pada protein H antara virus campak liar

L.G Alexander (1963) says that it’s hard to define exactly what a poem is and to state why it gives us pleasure. Every poem is unique and has special qualities of its own so if

Kebijakan penanggulangan terhadap malpraktik profesi medis atau malpraktik di bidang kesehatan ini, selain diatur di dalam Kitab Undang-Undang Hukum Pidana juga telah diatur di

Daya listrik yang disediakan oleh PLTS sebesar 5000 W untuk pemakaian selama 10 jam, menggunakan panel surya sebanyak 40 panel, daya puncak setiap panel surya 250 WP,

Setelah melakukan pendaftaran user baru oleh admin seperti yang dapat dilihat pada Gambar 4.4 di atas, maka pada saat yang bersamaan juga user baru tersebut akan diminta untuk

Tujuan DPM-LUEP untuk pembelian gabah/beras petani adalah : (a) Menjaga stabilitas harga gabah/beras yang diterima petani pada tingkat yang wajar; (b) Meningkatkan pendapatan

Kristal oranye kalium dikromat ditambahkan dalam suspensi dingin asam oksalat secara serentak yang disertai dengan pengadukan secara kontinu sehingga terjadi reaksi

Pada minggu pertama pekerjaan selesai lebih cepat dari pada rencana dengan menelan biaya di atas anggaran., sedangkan pada minggu ke dua hingga minggu ke sebelas