Lecture 9 - Generic Collections
Lecture 9 - Generic Collections
International University
School of Computer Science and Engineering
Generic Collections
(IT069IU)
🌐 leduytanit.com 1
Previously,
- Mid-term Exam
- Possible Topics
- Format
- GUI in Java
- Swing Components
- Swing vs JavaFX vs AWT
- JOption-Panel (DialogBox)
- Java 2D API
- Java Coordinate System
- Draw Lines
- Draw Rectangles and Ovals
- Draw Colors
- Draw Polygons and Polylines
- Text Fields, Buttons and Menu Nagivations.
- Event Handler (Mouse & Keyboard)
- Layout:
- BorderLayout Frame & GridLayoutFrame 2
Agenda
- Mid-term Exam Result
- Score Distribution
- Statistics
- Solutions
- Java Generic Collections
- Type-Wrapper Classes for Primitive Types
- Autoboxing vs Auto-unboxing
- List
- ArrayList
- Vector
- LinkedList
- Sets
- HashSet
- TreeSet
- Maps
- Hashtable
- HashMap
- TreeMaps
- HackerRank
- Introduction 3
- Coding Challenge
Mid-term Result Attended: 73
(91.25%)
Missed: 7 (9.59%)
Failed: 16
(21.92%)
Passed: 57
(78.08%)
Average Score (Mean): 64.3
Standard Deviation Score: 22.63
4
Mid-Term Exam Coding Solution
5
ArrayList and beyond!
- We introduced the generic ArrayList collection—a dynamically
resizable array-like data structure that stores references to objects of a
type.
- In this lecture, we continue our discussion of the Java collections
framework, which contains many other prebuilt generic data-
structures.
- Some examples of collections are your favorite songs stored on your
smartphone or media player, your contacts list, the cards you hold in a
card game, the members of your favorite sports team and the courses
you take in school.
6
Collections
- Java Collections framework:
- Prebuilt data structures.
- A data structure is a particular way of organizing data so that it can be used effectively.
- Interfaces and Methods for manipulating those data structures.
- A collection is a data structure—actually, an object—that can hold references to other
objects.
- Usually, collections contain references to objects that are all of the same type.
7
8
Interface Collection and Class Collections
- Interface Collection is the root interface from which interfaces Set, Queue and List
are derived.
- Interface Set defines a collection that does not contain duplicates.
- Interface Queue defines a collection that represents a waiting line.
- Interface Collection contains bulk operations for adding, clearing and comparing
objects in a collection.
- A Collection can be converted to an array.
- Interface Collection provides a method that returns an Iterator object, which
allows a program to loop the collection and modify elements from the collection
during the iteration.
- Class Collections provides static methods that search, sort and perform other
operations on collections.
9
Collection is not 100% compatible with primitive data types
10
Type-Wrapper Classes for Primitive Types
11
- Each of the numeric type-wrapper classes extends superclass Number.
- The type-wrapper classes are final classes, so you cannot extend them.
12
Autoboxing and Auto-Unboxing
- A boxing conversion converts a value of a primitive type to an object of the
corresponding type-wrapper class.
- An unboxing conversion converts an object of a type-wrapper class to a value
of the corresponding primitive type.
- These conversions can be performed automatically (called autoboxing and
auto-unboxing).
- Example:
13
Let’s talk about List!
- List interface:
- ArrayList, Vector, and LinkedList
14
List
- A List is a Collection that can contain duplicate elements.
- Fist index of a List is zero.
- In addition to the methods inherited from Collection, List provides methods
for manipulating elements via their indices, manipulating a specified range of
elements, searching for elements and obtaining a ListIterator to access the
elements.
- Interface List is implemented by several classes, including ArrayList, Vector,
and LinkedList.
- Autoboxing occurs when you add primitive-type values to objects of these
classes, because they store only references to objects.
15
ArrayList vs Vector
- Both are resizable-array implementations of List.
- The primary difference between ArrayList and Vector:
- Vectors are synchronized by default.
- ArrayLists are not synchronized.
- For example, if one thread is performing an add operation, then there can be another
thread performing a remove operation in a multithreading environment.
- Vector is synchronized, which means only one thread at a time can access the code,
while ArrayList is not synchronized, which means multiple threads can work on
ArrayList at the same time. Therefore, ArrayList is faster.
- Unsynchronized collections provide better performance than synchronized ones.
- For this reason, ArrayList is typically preferred over Vector in programs that do not
share a collection among threads.
16
List Methods
- List method add adds an item to the end of a list.
- List method size returns the number of elements.
- List method get retrieves an individual element’s value from the specified
index.
- Collection method iterator gets an Iterator for a Collection.
- Iterator method hasNext determines whether a Collection contains more
elements.
- Returns true if another element exists and false otherwise.
- Iterator method next obtains a reference to the next element.
- Collection method contains determine whether a Collection contains a
specified element.
- Iterator method remove removes the current element from a Collection.
17
18
LinkedList
- Inserting an element between existing elements of an ArrayList or Vector is
an inefficient operation.
- A LinkedList enables efficient insertion (or removal) of elements in the
middle of a collection.
- A LinkedList can be used to create stacks, queues and deques (double-ended
queues).
19
List Methods
- List method addAll appends all elements of a collecton to the end of a
List.
- List method listIterator gets A List’s bidirectional iterator.
- String method toUpperCase gets an uppercase version of a String.
- List-Iterator method set replaces the current element to which the iterator
refers with the specified object.
- List method subList obtains a portion of a List.
- This is a so-called range-view method, which enables the program to view a
portion of the list.
- List method clear remove the elements of a List.
- List method size returns the number of items in the List.
- ListIterator method hasPrevious determines whether there are more
elements while traversing the list backward.
- ListIterator method previous gets the previous element from the list.
20
21
22
LinkedList Methods
23
Convert from Array to List, and List to Array
24
LinkedList To Array
25
Collection Methods
Class Collections provides several high-performance algorithms for manipulating collection
elements. The algorithms are implemented as static methods.
26
Method sort
27
Collection.sort()
28
Collection.sort() in Reverse Order
29
30
Method shuffle
- Method shuffle randomly orders a List’s elements.
31
32
33
Methods reverse, fill, copy, max and min
- Collections method reverse reverses the order of the elements in a
List
- Method fill overwrites elements in a List with a specified value.
- Method copy takes two arguments—a destination List and a source
List.
- Each source List element is copied to the destination List.
- The destination List must be at least as long as the source List; otherwise, an
IndexOutOfBoundsException occurs.
- If the destination List is longer, the elements not overwritten are unchanged.
- Methods min and max each operate on any Collection.
- Method min returns the smallest element in a Collection, and method max returns
the largest element in a Collection.
34
35
Method binarySearch
36
37
Methods addAll, frequency and disjoint
38
39
Sets
- A Set is an unordered Collection of unique elements (i.e., no duplicate
elements).
- The collections framework contains several Set implementations,
including HashSet and TreeSet.
- HashSet stores its elements in a hash table, and TreeSet stores its
elements in a tree.
40
41
Maps
- Maps associate keys to values.
- The keys in a Map must be unique, but the associated values need not be.
- If a Map contains both unique keys and unique values, it is said to implement a one-to-one
mapping.
- If only the keys are unique, the Map is said to implement a many-to-one mapping—many keys
can map to one value.
- Three of the several classes that implement interface Map are Hashtable,
HashMap and TreeMap.
- Hashtables and HashMaps store elements in hash tables, and TreeMaps
store elements in trees.
- TreeMaps keeps the key in sorted order.
- Terms:
- "Map" is used by Java, C++
- "Dictionary" is used by .Net, Python
- "Associative array" is used by PHP
42
Maps
- Map method containsKey determines whether a key is in a map.
- Map method put creates a new entry in the map or replaces an
existing entry’s value.
- Method put returns the key’s prior associated value, or null if the key was not
in the map.
- Map method get obtain the specified key’s associated value in the
map.
- HashMap method keySet returns a set of the keys.
- Map method size returns the number of key/value pairs in the Map.
- Map method isEmpty returns a boolean indicating whether the Map is
empty.
43
44
Three ways to loop through a Collection
- The classic array index loop where you have the index of the element:
- Loop through with Iterator where you do not need any index of elements, and you
can access them or remove or modify them:
- Loop through with Iterator where you do not need any index of elements, and to
only access them without removing or modifying them:
45
HackerRank
- HackerRank is a place where programmers from all over the world come
together to solve coding problem to prepare for job interviews.
- https://www.hackerrank.com/interview/interview-preparation-kit
46
Get Used To HackerRank!
https://www.hackerrank.com/domains/tutorials/30-days-of-code
https://www.hackerrank.com/challenges/30-hello-world/problem
47
Challenge Time!
Real Job Interview Question: Ransom Note
https://www.hackerrank.com/challenges/ctci-ransom-note/problem
Hint: you should use HashMap.
48
Recap
- Mid-term Exam Result
- Score Distribution
- Statistics
- Solutions
- Java Generic Collections
- Type-Wrapper Classes for Primitive Types
- Autoboxing vs Auto-unboxing
- List
- ArrayList
- Vector
- LinkedList
- Sets
- HashSet
- TreeSet
- Maps
- Hashtable
- HashMap
- TreeMaps
- HackerRank
- Introduction 49
- Coding Challenge
Thank you for your listening!
50