IT 405: KPLBO MATERI 9 RELASI ANTAR OBJEK III Ayi Purbasari, ST., MT. If-Unpas, 2014
OUTLINE
Collections
Tipe Collections
Array
ArrayList
COLLECTIONS
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.
Collection dapat dianalogikan dengan sebuah box telur yang menampung telurtelur. Objek collection berperan seperti box telur, sedangkan objek-objek elemennya berperan seperti telur yang ditampung oleh objek box.
COLLECTIONS Di Java, ada beberapa kelas collection. Seperti kelas pada umumnya, collection perlu di-instansiasi-kan. CollectionType<ElementType> x = new CollectionType<ElementType>();
Contoh: ArrayList<Student> x = new ArrayList<Student>();
COLLECTIONS 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: ArrayList<Student> x = new ArrayList<>();
Collection mengelola referensi untuk objek yang berada pada memori, diluar collection tersebut
Maka dari itu, sebenarnya collection lebih tepat dianalogikan dengan buku alamat, yang menyimpan alamatalamat (references) dari orang-orang (objek-objek) yang ingin kita hubungi.
ENKAPSULASI PADA COLLECTIONS
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 collection)
TIPE UMUM PADA COLLECTIONS Collections
Ordered lists Dictionaries Sets
ORDERED LIST 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: ArrayList, LinkedList, Stack, Vector
ORDERED LIST
DICTIONARIES
Disebut juga “map”. Menggunakan sebuah “kunci” untuk mencari objek tertentu.
Contoh di Java: HashMap, Hashtable, TreeMap
DICTIONARIES
SETS
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
ARRAY 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.).
DECLARING AND INSTANTIATING ARRAYS 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. Student[] x = new Student[20];
ACCESSING INDIVIDUAL ARRAY ELEMENTS // 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];
INITIALIZING ARRAY CONTENTS 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];
then we’d wind up with an array object filled with null values.
MANIPULATING ARRAYS OF OBJECTS 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;
ILUSTRASI
MANIPULATING ARRAYS OF OBJECTS .. (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());
}
MANIPULATING ARRAYS OF OBJECTS ., (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()); } }
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
IMPORT DIRECTIVES AND PACKAGES 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
y = new java.util.ArrayList(); // etc.
}
}
THE ARRAYLIST CLASS
ARRAYLIST FEATURES .. (1) Insert dengan metode void add() Contoh:
ArrayList<Student> students = new ArrayList<Student>(); Student s = new Student(); students.add(s);
atau students.add(0, s);
ARRAYLIST FEATURES .. (2)
Insert banyak elemen dengan metode addAll ()
ARRAYLIST FEATURES .. (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: // if // if
Tests for containment: the first test will return false ... (x.contains(s2)) { ... } ... while the second will return true. (x.contains(s3)) { ... }
ILUSTRASI
ARRAYLIST FEATURES .. (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.
ITERATING THROUGH ARRAYLISTS for (type referenceVariable : collectionName) { // Pseudocode.
manipulate the referenceVariable as desired } for example: for (Student s : students) { System.out.println(s.getName()); }
COPYING THE CONTENTS OF AN ARRAYLIST INTO AN ARRAY .. (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"));
COPYING THE CONTENTS OF AN ARRAYLIST INTO AN ARRAY .. (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: students.toArray(copyOfStudents);
COPYING THE CONTENTS OF AN ARRAYLIST INTO AN ARRAY .. (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()); }
COPYING THE CONTENTS OF AN ARRAYLIST INTO AN ARRAY .. (4)
Output program
Ilustrasi
PUSTAKA
Barker, Jacquie. Beginning Java Objects From Concepts to Code, Second Edition. Appress. 2005.