• Tidak ada hasil yang ditemukan

IT 405: KPLBO MATERI 9 RELASI ANTAR OBJEK III. Ayi Purbasari, ST., MT. If-Unpas, 2014

N/A
N/A
Protected

Academic year: 2021

Membagikan "IT 405: KPLBO MATERI 9 RELASI ANTAR OBJEK III. Ayi Purbasari, ST., MT. If-Unpas, 2014"

Copied!
37
0
0

Teks penuh

(1)

IT 405: KPLBO

M

ATERI

9 R

ELASI

A

NTAR

O

BJEK

III

Ayi Purbasari, ST., MT. If-Unpas, 2014

(2)

O

UTLINE

Collections Collections Tipe

(3)

C

OLLECTIONS

 Adalah sebuah cara untuk mengumpulkan objek-objek yang telah kita ciptakan, sehingga mereka dapat dikelola sebagai sebuah

grup dan dioperasikan secara kolektif.  Contoh:

 Seorang dosen menginginkan untuk melihat seluruh mahasiswa yang mengikuti kelasnya untuk memberikan nilai akhir pada mereka.

(4)

Collection dapat

dianalogikan dengan sebuah box telur yang menampung

telur-telur. Objek collection berperan seperti box telur, sedangkan

objek-objek

elemennya berperan seperti telur yang

ditampung oleh objek box.

(5)

C

OLLECTIONS

 Di Java, ada beberapa kelas collection.

 Seperti kelas pada umumnya, collection perlu di-instansiasi-kan.  CollectionType<ElementType> x = new

CollectionType<ElementType>();

 Contoh:

(6)

C

OLLECTIONS

 Pada Java 7 (jdk 1.7.0 ke atas), instansiasi kelas collection mengalami sedikit perubahan.

 Dimungkinkan untuk membuat instansiasi “diamond”, seperti pada contoh berikut

CollectionType<ElementType> x = new

CollectionType<>();

 Contoh:

(7)

Collection mengelola referensi untuk objek yang berada pada memori, diluar collection

(8)

Maka dari itu, sebenarnya collection lebih tepat dianalogikan dengan buku alamat, yang menyimpan

alamat-alamat (references) dari orang-orang (objek-objek) yang ingin kita hubungi.

(9)

E

NKAPSULASI PADA

C

OLLECTIONS

 Kelas collection pada bahasa apapun, minimal mempunyai method-method sebagai berikut:

 add (menambahkan objek)  remove (menghapus objek)

 retrieve (mencari sebuah objek)

 iterate (menelusuri objek-objek, dengan urutan tertentu)  count (menghitung jumlah objek pada collection)

 find (menjawab true/false, apakah sebuah objek ada atau tidak ada pada

(10)

T

IPE

U

MUM PADA

C

OLLECTIONS

Collections

Ordered lists

Dictionaries

Sets

(11)

O

RDERED

L

IST

 Adalah tipe collection yang memungkinkan kita untuk

menambahkan objek dengan urutan tertentu dan kemudian mengambilnya dengan urutan yang sama.

 Objek tertentu juga dapat diambil dengan menggunakan posisinya pada list (misalnya pertama, terakhir, atau ke-n).

 Contoh di Java:

(12)
(13)

D

ICTIONARIES

 Disebut juga “map”. Menggunakan sebuah “kunci” untuk mencari objek tertentu.

 Contoh di Java:

(14)
(15)

S

ETS

 Adalah kelas collection yang tidak berurutan. Artinya, kita tidak dapat mengambil objek dengan menggunakan urutan seperti pada ordered list.

Set tidak

memperbolehkan masukan duplikat.

Contoh Set di Java adalah HashSet dan TreeSet

(16)

A

RRAY SEBAGAI SIMPLE COLLECTION

 One simple type of collection that you may already be familiar with from your work with other programming languages—OO or

otherwise—is an array.

 As mentioned in passing earlier in the chapter, an array is a simple type of ordered list.

 We can think of an array as a series of compartments, with each compartment sized appropriately for whatever type of data the array as a whole is intended to hold.

 Arrays typically hold items of like type—for example, int(eger)s; or char(acter)s; or, in an OO language, object references (references to Student objects, or to Course objects, or to Professor objects, etc.).

(17)

D

ECLARING AND

I

NSTANTIATING

A

RRAYS datatype[] x;

int[] x;

// We declare variable x as a // reference to an array

// object that will be used to // store 20 Student object

// references.

(18)

A

CCESSING

I

NDIVIDUAL

A

RRAY

E

LEMENTS

// Declare an array capable of holding three double values. double[] data = new double[3];

// Set the FIRST (zeroeth) element to 4.7. data[0] = 4.7;

// Details omitted ...

// Access the LAST element's value. double temp = data[2];

(19)

I

NITIALIZING

A

RRAY

C

ONTENTS

String[] names = { "Steve", "Jacquie", "Chloe", "Shylow", "Baby Grode" };

atau

String[] names = new String[5]; names[0] = "Steve";

names[1] = "Jacquie"; names[2] = "Chloe"; names[3] = "Shylow";

names[4] = "Baby Grode";

if we declare and instantiate an array intended to hold references to objects, as in

Student[] studentBody = new Student[100];

(20)

M

ANIPULATING

A

RRAYS OF

O

BJECTS

studentBody[0] = new Student("Fred"); studentBody[1] = new Student("Mary"); // etc.

or

Student s = new Student("Fred"); studentBody[0] = s;

// Reuse s!

s = new Student("Mary"); studentBody[1] = s;

(21)
(22)

M

ANIPULATING

A

RRAYS OF

O

BJECTS

.. (2)

// When we first instantiate an array of object references, all cells contain the // value null.

Student[] students = new Student[3];

// Store a Student object reference in cells 0 and 1, but leave // cell 2 empty (i.e., it retains its default value of null). students[0] = new Student("Elmer");

students[1] = new Student("Klemmie");

// Try to step through the array, printing each Student's name. // There's a "land mine" lurking at element 2!!!

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

System.out.println(students[i].getName()); }

(23)

M

ANIPULATING

A

RRAYS OF

O

BJECTS

., (3)

// Step through all elements of the array. for (int i = 0; i < students.length; i++) {

// Check for the presence of a valid object reference // before trying to "talk to" it via dot notation.

if (studentBody[i] != null) {

System.out.println(studentBody[i].getName()); }

(24)

A MORE SOPHISTICATED TYPE OF COLLECTION:

THE ARRAYLIST CLASS

Import Directives and Packages

java.util: This package contains a number of utility classes, such as the Java collection classes that you’re learning about in this chapter

(25)

I

MPORT

D

IRECTIVES AND

P

ACKAGES

import java.util.*; or

import java.util.ArrayList;

// Note: NO import directive! public class Simple {

public static void main(String[] args) {

java.util.ArrayList<Student> x = new java.util.ArrayList<Student>(); java.util.ArrayList<Professor> y = new java.util.ArrayList<Professor>(); // etc. } }

(26)
(27)

A

RRAY

L

IST

F

EATURES

.. (1)

 Insert dengan metode void add()  Contoh:

ArrayList<Student> students = new ArrayList<Student>(); Student s = new Student();

students.add(s);

atau

(28)

A

RRAY

L

IST

F

EATURES

.. (2)

 Insert banyak elemen dengan metode addAll ()

(29)

A

RRAY

L

IST

F

EATURES

.. (3)

 void clear(): Removes all elements from the collection, rendering it empty. Contoh:

 students.clear();

 boolean contains(Object element): Returns true if the specific object referenced by the argument is also referenced by the ArrayList,

and false otherwise. Contoh:

// Tests for containment: the first test will return false ... if (x.contains(s2)) { ... }

// ... while the second will return true. if (x.contains(s3)) { ... }

(30)
(31)

A

RRAY

L

IST

F

EATURES

.. (4)

 int size(): Returns a count of the number of elements currently referenced by the

ArrayList. An empty ArrayList will report a size of 0.

 boolean isEmpty(): Returns true if the ArrayList in question contains no elements, and

false otherwise.

 boolean remove(Object element): Locates and removes a single instance of the specific

object referred to by the argument from the ArrayList, closing up the hole that would

otherwise be left behind. It returns true if such an object was found and removed, or false if the object wasn’t found.

(32)

I

TERATING

T

HROUGH

A

RRAY

L

ISTS

for (type referenceVariable : collectionName) { // Pseudocode.

manipulate the referenceVariable as desired }

for example:

for (Student s : students) {

System.out.println(s.getName()); }

(33)

C

OPYING THE

C

ONTENTS OF AN

A

RRAY

L

IST INTO AN

A

RRAY

.. (1)

 type[] toArray(type[] arrayRef)  Contoh:

 First, we’ll create an ArrayList named students, “stuffing” it with three Student references:

ArrayList<Student> students = new ArrayList<Student>();

students.add(new Student("Herbie")); students.add(new Student("Klemmie")); students.add(new Student("James"));

(34)

C

OPYING THE

C

ONTENTS OF AN

A

RRAY

L

IST INTO AN

A

RRAY

.. (2)

 Next, we’ll declare and instantiate an array named copyOfStudents that’s designed to be just the right size to hold the contents of the students ArrayList—note the use of a nested call to students.size() to accomplish this:

Student[] copyOfStudents = new Student[students.size()];

 Then, to copy the contents of the ArrayList into the

copyOfStudents array, we simply have to invoke the toArray

method on students, passing in copyOfStudents as an argument:

(35)

C

OPYING THE

C

ONTENTS OF AN

A

RRAY

L

IST INTO AN

A

RRAY

.. (3)

 Let’s verify that the copy works by iterating first through the ArrayList, then through the array, printing the names of the Student objects referenced by each:

System.out.println("The ArrayList contains the following students:");

for (Student s : students) {

System.out.println(s.getName()); }

System.out.println();

System.out.println("The array contains the following students:"); for (int i = 0; i < copyOfStudents.length; i++) {

System.out.println(copyOfStudents[i].getName()); }

(36)

C

OPYING THE

C

ONTENTS OF AN

A

RRAY

L

IST INTO AN

A

RRAY

.. (4)

(37)

P

USTAKA

 Barker, Jacquie. Beginning Java Objects From Concepts to Code, Second Edition. Appress. 2005.

Referensi

Dokumen terkait