IT 405: KPLBO
M
ATERI9 R
ELASIA
NTARO
BJEKIII
Ayi Purbasari, ST., MT. If-Unpas, 2014
O
UTLINECollections Collections Tipe
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.
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.
C
OLLECTIONS Di Java, ada beberapa kelas collection.
Seperti kelas pada umumnya, collection perlu di-instansiasi-kan. CollectionType<ElementType> x = new
CollectionType<ElementType>();
Contoh:
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:
Collection mengelola referensi untuk objek yang berada pada memori, diluar collection
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.
E
NKAPSULASI PADAC
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
T
IPEU
MUM PADAC
OLLECTIONSCollections
Ordered lists
Dictionaries
Sets
O
RDEREDL
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:
D
ICTIONARIES Disebut juga “map”. Menggunakan sebuah “kunci” untuk mencari objek tertentu.
Contoh di Java:
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
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.).
D
ECLARING ANDI
NSTANTIATINGA
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.
A
CCESSINGI
NDIVIDUALA
RRAYE
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];
I
NITIALIZINGA
RRAYC
ONTENTSString[] 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];
M
ANIPULATINGA
RRAYS OFO
BJECTSstudentBody[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;
M
ANIPULATINGA
RRAYS OFO
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()); }
M
ANIPULATINGA
RRAYS OFO
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()); }
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
I
MPORTD
IRECTIVES ANDP
ACKAGESimport 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. } }
A
RRAYL
ISTF
EATURES.. (1)
Insert dengan metode void add() Contoh:
ArrayList<Student> students = new ArrayList<Student>(); Student s = new Student();
students.add(s);
atau
A
RRAYL
ISTF
EATURES.. (2)
Insert banyak elemen dengan metode addAll ()
A
RRAYL
ISTF
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)) { ... }
A
RRAYL
ISTF
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.
I
TERATINGT
HROUGHA
RRAYL
ISTSfor (type referenceVariable : collectionName) { // Pseudocode.
manipulate the referenceVariable as desired }
for example:
for (Student s : students) {
System.out.println(s.getName()); }
C
OPYING THEC
ONTENTS OF ANA
RRAYL
IST INTO ANA
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"));
C
OPYING THEC
ONTENTS OF ANA
RRAYL
IST INTO ANA
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:
C
OPYING THEC
ONTENTS OF ANA
RRAYL
IST INTO ANA
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()); }
C
OPYING THEC
ONTENTS OF ANA
RRAYL
IST INTO ANA
RRAY.. (4)
P
USTAKA Barker, Jacquie. Beginning Java Objects From Concepts to Code, Second Edition. Appress. 2005.