Post on 11-Nov-2014
description
Introduction to Introduction to Java 2 Java 2
ProgrammingProgrammingLecture 5Lecture 5
Array and CollectionsArray and CollectionsRef: Ref: www.ldodds.comwww.ldodds.com
Edited by Hoàng Văn Hậu – VTC Academy – Edited by Hoàng Văn Hậu – VTC Academy – THSoft co.,ltdTHSoft co.,ltd
https://play.google.com/store/apps/developer?https://play.google.com/store/apps/developer?id=THSoft+Co.,Ltdid=THSoft+Co.,Ltd
VTC Academy 2THSoft Co.,Ltd
IntroductionIntroduction Course ObjectivesCourse Objectives Organization of the BookOrganization of the Book
VTC Academy 3THSoft Co.,Ltd
Course ObjectivesCourse Objectives Upon completing the course, you will understandUpon completing the course, you will understand
Create, compile, and run Java programsCreate, compile, and run Java programs Primitive data typesPrimitive data types Java control flowJava control flow MethodsMethods Arrays Arrays (for teaching Java in two semesters, this could be the (for teaching Java in two semesters, this could be the
end)end) Object-oriented programmingObject-oriented programming Core Java classes (Swing, exception, Core Java classes (Swing, exception,
internationalization, multithreading, multimedia, I/O, internationalization, multithreading, multimedia, I/O, networking, Java Collections Framework)networking, Java Collections Framework)
VTC Academy 4THSoft Co.,Ltd
Course Objectives, cont.Course Objectives, cont.
You will be able to You will be able to Develop programs using Eclipse IDEDevelop programs using Eclipse IDE Write simple programs using Write simple programs using
primitive data types, control primitive data types, control statements, methods, and arrays.statements, methods, and arrays.
Create and use methodsCreate and use methods Write interesting projectsWrite interesting projects
VTC Academy 5THSoft Co.,Ltd
Session 05: GENERIC Session 05: GENERIC PROGRAMMING AND PROGRAMMING AND
COLLECTIONSCOLLECTIONS Generic classGeneric class ArraysArrays
Working with arraysWorking with arrays Java API support for arraysJava API support for arrays
Collection classesCollection classes Types of collectionTypes of collection Working with CollectionsWorking with Collections
VTC Academy 6THSoft Co.,Ltd
Definition of a simple Definition of a simple generic classgeneric class
classclass Pair <T> { Pair <T> { publicpublic T first; T first; publicpublic T second; T second;
publicpublic Pair (T f, T s) { first = f; second = s; } Pair (T f, T s) { first = f; second = s; } publicpublic Pair () { first = Pair () { first = nullnull; second = ; second = nullnull; }; }}}
you instantiate the generic class by substituting you instantiate the generic class by substituting actual types for type variables, as: actual types for type variables, as: Pair <String> Pair <String>
you can you can thinkthink the result as a class with a the result as a class with a constructorconstructor
publicpublic Pair (String f, String s) Pair (String f, String s), etc . ., etc . .
you can then use the instantiated generic class you can then use the instantiated generic class asas it were a normal class (almost):it were a normal class (almost):
Pair <String> pair = Pair <String> pair = newnew Pair <String> ("1","2"); Pair <String> ("1","2");
VTC Academy 7THSoft Co.,Ltd
Multiple type parameters Multiple type parameters allowedallowed
you can have multiple type parametersyou can have multiple type parameters
classclass Pair <T, U> { Pair <T, U> { publicpublic T first; T first; publicpublic U second; U second;
publicpublic Pair (T x, U y) { first = x; second = Pair (T x, U y) { first = x; second = y; }y; } publicpublic Pair () { first = Pair () { first = nullnull; second = ; second = nullnull; }; }}}
to instantiate: to instantiate: Pair <String, Number> Pair <String, Number>
VTC Academy 8THSoft Co.,Ltd
How to use generic classHow to use generic class
PairPair<String> k = <String> k = newnew PairPair<String>("abc", "xyz");<String>("abc", "xyz");
Pair<double> d = new Pair<T>();// errorPair<double> d = new Pair<T>();// error
PairPair<Double> d = <Double> d = newnew PairPair<Double>();<Double>();
System.System.outout.println(k.getFirst() + k.second);.println(k.getFirst() + k.second);
Pair<String, Double> Pair<String, Double> kk = = newnew Pair<String, Pair<String, Double>("xxxx", 10.8);Double>("xxxx", 10.8);
System.System.outout.println(k.first + k.second);.println(k.first + k.second);
Illustration on code
VTC Academy 9THSoft Co.,Ltd
Java Arrays – CopyingJava Arrays – Copying
Don’t copy arrays “by hand” by Don’t copy arrays “by hand” by looping over the arraylooping over the array
The System class has an The System class has an arrayCopyarrayCopy method to do this efficientlymethod to do this efficiently
int array1[] = new int[10];int array1[] = new int[10];int array2[] = new int[10];int array2[] = new int[10];//assume we add items to array1//assume we add items to array1
//copy array1 into array2//copy array1 into array2System.arrayCopy(array1, 0, array2, 0, 10);System.arrayCopy(array1, 0, array2, 0, 10);//copy last 5 elements in array1 into first 5 of array2//copy last 5 elements in array1 into first 5 of array2System.arrayCopy(array1, 5, array2, 0, 5);System.arrayCopy(array1, 5, array2, 0, 5);
VTC Academy 10THSoft Co.,Ltd
Java Arrays – SortingJava Arrays – Sorting
Again no need to do this “by hand”.Again no need to do this “by hand”. The java.util.Arrays class has The java.util.Arrays class has
methods to sort different kinds of methods to sort different kinds of arraysarrays
int myArray[] = new int[] {5, 4, 3, 2, 1};int myArray[] = new int[] {5, 4, 3, 2, 1};java.util.Arrays.sort(myArray);java.util.Arrays.sort(myArray);//myArray now holds 1, 2, 3, 4, 5//myArray now holds 1, 2, 3, 4, 5
Sorting arrays of Sorting arrays of objectsobjects is involves is involves some extra work, as we’ll see later…some extra work, as we’ll see later…
VTC Academy 11THSoft Co.,Ltd
Java ArraysJava Arrays
AdvantagesAdvantages Very efficient, quick to access and add toVery efficient, quick to access and add to Type-safe, can only add items that match the Type-safe, can only add items that match the
declared type of the arraydeclared type of the array DisadvantagesDisadvantages
Fixed size, some overhead in copying/resizingFixed size, some overhead in copying/resizing Can’t tell how many items in the array, just Can’t tell how many items in the array, just
how large it was declared to behow large it was declared to be Limited functionality, need more general Limited functionality, need more general
functionalityfunctionality
VTC Academy 12THSoft Co.,Ltd
Java CollectionsJava Collections
What are they?What are they? A number of pre-packaged implementations of A number of pre-packaged implementations of
common ‘container’ classes, such as common ‘container’ classes, such as LinkedLists, Sets, etc.LinkedLists, Sets, etc.
Part of the Part of the java.utiljava.util package. package. AdvantagesAdvantages
Very flexible, can hold any kind of objectVery flexible, can hold any kind of object DisadvantagesDisadvantages
Not as efficient as arrays (for some uses)Not as efficient as arrays (for some uses) Not type-safe. Store references to Not type-safe. Store references to ObjectObject
VTC Academy 13THSoft Co.,Ltd
Java CollectionsJava Collections
Two Types of ContainersTwo Types of Containers CollectionsCollections
Group of objects, which may restricted or Group of objects, which may restricted or manipulated in some waymanipulated in some way
E.g. an ordered to make a List or LinkedListE.g. an ordered to make a List or LinkedList E.g. a Set, an unordered group which can only E.g. a Set, an unordered group which can only
contain one of each itemcontain one of each item MapsMaps
Associative array, Dictionary, Lookup Table, Associative array, Dictionary, Lookup Table, HashHash
A group of name-value pairsA group of name-value pairs
VTC Academy 14THSoft Co.,Ltd
Java CollectionsJava Collections
VTC Academy 15THSoft Co.,Ltd
Java CollectionsJava Collections
Several implementations associated Several implementations associated with each of the basic interfaceswith each of the basic interfaces
Each has its own Each has its own advantages/disadvantagesadvantages/disadvantages
MapsMaps HashMap, SortedMapHashMap, SortedMap
ListsLists ArrayListArrayList
SetsSets HashSet, SortedSetHashSet, SortedSet
VTC Academy 16THSoft Co.,Ltd
Java Collections – The Java Collections – The BasicsBasics
HashMap and ArrayList are most HashMap and ArrayList are most commonly encounteredcommonly encountered
Usual object creation syntax Usual object creation syntax Generally hold references to the interface Generally hold references to the interface
and not the specific collectionand not the specific collection Can then process them genericallyCan then process them generically
List<Object> List<Object> myListmyList = = newnew ArrayList<Object>(); ArrayList<Object>();
List<BigDecimal> List<BigDecimal> otherListotherList = = newnew ArrayList<BigDecimal>(5); ArrayList<BigDecimal>(5);
Map<String, String> myMap = Map<String, String> myMap = newnew HashMap() HashMap();;
Set<Float> Set<Float> thingsthings = = newnew HashSet<Float>(); HashSet<Float>();
VTC Academy 17THSoft Co.,Ltd
Java Collections – Adding Java Collections – Adding ItemsItems
For Collections, use For Collections, use add()add()List myList = new ArrayList();List myList = new ArrayList();
myList.add(“A String”);myList.add(“A String”);
myList.add(“Other String”);myList.add(“Other String”);
For Maps, use For Maps, use put()put()Map myMap = new HashMap();Map myMap = new HashMap();
myMap.put(“google”, “http://www.google.com”);myMap.put(“google”, “http://www.google.com”);
mpMap.put(“yahoo”, “http://www.yahoo.com”);mpMap.put(“yahoo”, “http://www.yahoo.com”);
VTC Academy 18THSoft Co.,Ltd
Java Collections – Java Collections – CopyingCopying
Very easy, just use addAll()Very easy, just use addAll()
List myList = new ArrayList();List myList = new ArrayList();
//assume we add items to the list//assume we add items to the list
List otherList = new ArrayList();List otherList = new ArrayList();
myList.addAll(myList);myList.addAll(myList);
VTC Academy 19THSoft Co.,Ltd
Collections – Getting Collections – Getting Individual ItemsIndividual Items
Use Use get()get() Note that we have to Note that we have to castcast the object to its the object to its
original type.original type. Collections…Collections…String s = (String)myList.get(1); //get first elementString s = (String)myList.get(1); //get first element
String s2 = (String)myList.get(10); //get tenth elementString s2 = (String)myList.get(10); //get tenth element
Maps…Maps…String s = (String)myMap.get(“google”);String s = (String)myMap.get(“google”);
String s2 = (String)mpMap.get(“yahoo”);String s2 = (String)mpMap.get(“yahoo”);
VTC Academy 20THSoft Co.,Ltd
Collections – Getting all Collections – Getting all itemsitems
For Lists, we could use a For Lists, we could use a forfor loop, and loop, and loop through the list to loop through the list to get()get() each item each item
But this doesn’t work for Maps.But this doesn’t work for Maps. To allow generic handling of collections, To allow generic handling of collections,
Java defines an object called an Java defines an object called an IteratorIterator An object whose function is to walk through An object whose function is to walk through
a Collection of objects and provide access to a Collection of objects and provide access to each object in sequenceeach object in sequence
VTC Academy 21THSoft Co.,Ltd
Collections – Getting all Collections – Getting all itemsitems
Get an iterator using the Get an iterator using the iterator()iterator() methodmethod
Iterator objects have three methods:Iterator objects have three methods: next()next() – gets the next item in the collection – gets the next item in the collection hasNext()hasNext() – tests whether it has reached – tests whether it has reached
the endthe end remove()remove() – removes the item just returned – removes the item just returned
Basic iterators only go forwardsBasic iterators only go forwards Lists objects have a ListIterator that can go Lists objects have a ListIterator that can go
forward and backwardforward and backward
VTC Academy 22THSoft Co.,Ltd
Collections – Getting all Collections – Getting all itemsitems
Simple example:Simple example:List myList = new ArrayList();List myList = new ArrayList();
//we add items//we add items
Iterator iterator = myList.iterator();Iterator iterator = myList.iterator();
while (iterator.hasNext())while (iterator.hasNext())
{{
String s = (String)iterator.next();String s = (String)iterator.next();
//do something with it//do something with it
}}
VTC Academy 23THSoft Co.,Ltd
Collections – Other Collections – Other FunctionsFunctions
The The java.util.Collectionsjava.util.Collections class has class has many useful methods for working many useful methods for working with collectionswith collections min, max, sort, reverse, search, shufflemin, max, sort, reverse, search, shuffle
Virtually all require your objects to Virtually all require your objects to implement an extra interface, called implement an extra interface, called ComparableComparable
VTC Academy 24THSoft Co.,Ltd
Collections – ComparableCollections – Comparable
The Comparable interface labels objects that The Comparable interface labels objects that can be compared to one another.can be compared to one another. Allows sorting algorithms to be written to work on any Allows sorting algorithms to be written to work on any
kind of objectkind of object so long as they support this interfaceso long as they support this interface
Single method to implementSingle method to implementpublic int compareTo(Object o);public int compareTo(Object o);
Returns Returns A negative number of parameter is less than the A negative number of parameter is less than the
objectobject Zero if they’re equalZero if they’re equal A positive number if the parameter is greater than the A positive number if the parameter is greater than the
objectobject
VTC Academy 25THSoft Co.,Ltd
Collections – ComparatorCollections – Comparator
Like Comparable, but is a stand-alone Like Comparable, but is a stand-alone object used for comparing other objectsobject used for comparing other objects Useful when you want to use Useful when you want to use youryour criteria, criteria,
not that of the implementor of the object.not that of the implementor of the object. Or altering the behaviour of a systemOr altering the behaviour of a system
Many of the methods in the Collections Many of the methods in the Collections object all a Comparator to be specifiedobject all a Comparator to be specified
Again has single method:Again has single method:public int compare(Object obj1, Object obj2)public int compare(Object obj1, Object obj2)
VTC Academy 26THSoft Co.,Ltd
Action on classAction on class
Teacher Teacher hauc2@yahoo.comhauc2@yahoo.com 09843800030984380003 https://play.google.com/store/search?https://play.google.com/store/search?
q=thsoft+co&c=appsq=thsoft+co&c=apps
CaptionsCaptions MembersMembers