Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Lecture 9 - Generic Collections

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Lecture 9 - Generic Collections

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Vietnam National University of HCMC

International University
School of Computer Science and Engineering

Generic Collections

(IT069IU)

Le Duy Tan, Ph.D.


📧 ldtan@hcmiu.edu.vn

🌐 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

- But Collections only stores reference to objects so it cannot


store primitive data types.
- So we need to figure out how to store primitive data as an object
of a class.
- Introducing type-wrapper classes!

10
Type-Wrapper Classes for Primitive Types

- Type-Wrapper classes provide a way to use primitive data types


(int, char, short, byte, etc) as objects.
- Each primitive type has a corresponding type-wrapper class:
- Boolean, Byte, Character, Double, Float, Integer, Long and Short.
- Each type-wrapper class enables you to manipulate primitive-type
values as objects.
- They are in package java.lang.

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

- LinkedList method addLast adds an element to the end of a List.


- LinkedList method add also adds an element to the end of a List.
- LinkedList method addFirst adds an element to the beginning of a List.

23
Convert from Array to List, and List to Array

- Class Arrays provides static method asList to view an array as a List


collection.
- A List view allows you to manipulate the array as if it were a list.
- This is useful for adding the elements in an array to a collection and for sorting
array elements.
- Any modifications made through the List view change the array, and
any modifications made to the array change the List view.
- List method toArray gets an array from a List collection.

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

- Method sort sorts the elements of a List


- The elements must implement the Comparable interface.
- The order is determined by the natural order of the elements’ type as implemented by
a compareTo method.
- For example, the natural order for numeric values is ascending order, and the natural
order for Strings is based on their lexicographical ordering.
- Method compareTo is declared in interface Comparable and is sometimes called the
natural comparison method.
- The sort call may specify as a second argument a Comparator object that determines
an alternative ordering of the elements.

27
Collection.sort()

28
Collection.sort() in Reverse Order

- The Comparator interface is used for sorting a Collection’s elements in a


different order.
- The static Collections method reverseOrder returns a Comparator object
that orders the collection’s elements 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

- static Collections method binarySearch locates an object in a List.


- If the object is found, its index is returned.
- If the object is not found, binarySearch returns a negative value.
- Method binarySearch determines this negative value by first calculating the
insertion point and making its sign negative.
- Then, binarySearch subtracts 1 from the insertion point to obtain the return
value, which guarantees that method binarySearch returns positive numbers
(>= 0) if and only if the object is found.

36
37
Methods addAll, frequency and disjoint

- Collections method addAll takes two arguments—a Collection into which to


insert the new element(s) and an array that provides elements to be inserted.
- Collections method frequency takes two arguments—a Collection to be searched
and an Object to be searched for in the collection.
- Method frequency returns the number of times that the second argument appears in the
collection.
- Collections method disjoint takes two Collections and returns true if they have no
elements in common.

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

- Select your language to be Java 7.


- Type your code
- Press “Run Code” to test your code.
- When you are happy with your code, press “Submit Code” to let your code to
be tested against different test cases. If you passed all the test cases, then
you pass the 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!

“Motivation is what gets you started.


Habit is what keeps you going!”
Jim Ryun

50

You might also like