SlideShare une entreprise Scribd logo
1  sur  26
Introduction to Java 2
    Programming
                         Lecture 5
                  Array and Collections
                    Ref: www.ldodds.com
 Edited by Hoàng Văn Hậu – VTC Academy – THSoft co.,ltd
 https://play.google.com/store/apps/developer?id=THSoft+Co.,Ltd
Introduction
    Course Objectives
    Organization of the Book




VTC Academy      THSoft Co.,Ltd   2
Course Objectives
   Upon completing the course, you will understand
        Create, compile, and run Java programs
        Primitive data types
        Java control flow
        Methods
        Arrays (for teaching Java in two semesters, this could be the end)
        Object-oriented programming
        Core Java classes (Swing, exception, internationalization, multithreading,
         multimedia, I/O, networking, Java Collections Framework)




VTC Academy                 THSoft Co.,Ltd                     3
Course Objectives, cont.
    You will be able to
      Develop programs using Eclipse IDE
      Write simple programs using primitive data types,
       control statements, methods, and arrays.
      Create and use methods

      Write interesting projects




VTC Academy        THSoft Co.,Ltd          4
Session 05: GENERIC PROGRAMMING
             AND COLLECTIONS
   Generic class
   Arrays
       Working with arrays
       Java API support for arrays
   Collection classes
       Types of collection
       Working with Collections




VTC Academy            THSoft Co.,Ltd   5
Definition of a simple generic class
        class Pair <T> {
             public T first;
             public T second;
              public Pair (T f, T s) { first = f; second = s; }
              public Pair () { first = null; second = null; }
         }
     you instantiate the generic class by substituting actual types for
      type variables, as: Pair <String>
     you can think the result as a class with a constructor
             public Pair (String f, String s), etc . .
     you can then use the instantiated generic class as it were a normal
      class (almost):
             Pair <String> pair = new Pair <String> ("1","2");



VTC Academy                   THSoft Co.,Ltd                      6
Multiple type parameters allowed
     you can have multiple type parameters
       class Pair <T, U> {
           public T first;
           public U second;
            public Pair (T x, U y) { first = x; second = y; }
            public Pair () { first = null; second = null; }
        }

     to instantiate: Pair <String, Number>


VTC Academy            THSoft Co.,Ltd                7
How to use generic class
  Pair<String> k = new Pair<String>("abc", "xyz");
  Pair<double> d = new Pair<T>();// error
  Pair<Double> d = new Pair<Double>();
  System.out.println(k.getFirst() + k.second);

  Pair<String, Double> k = new Pair<String, Double>("xxxx", 10.8);
  System.out.println(k.first + k.second);




                                           Illustration on code
VTC Academy         THSoft Co.,Ltd             8
Java Arrays – Copying
   Don’t copy arrays “by hand” by looping over
    the array
   The System class has an arrayCopy method
    to do this efficiently
int array1[] = new int[10];
int array2[] = new int[10];
//assume we add items to array1

//copy array1 into array2
System.arrayCopy(array1, 0, array2, 0, 10);
//copy last 5 elements in array1 into first 5 of array2
System.arrayCopy(array1, 5, array2, 0, 5);


VTC Academy        THSoft Co.,Ltd           9
Java Arrays – Sorting
   Again no need to do this “by hand”.
   The java.util.Arrays class has methods to sort
    different kinds of arrays

int myArray[] = new int[] {5, 4, 3, 2, 1};
java.util.Arrays.sort(myArray);
//myArray now holds 1, 2, 3, 4, 5


   Sorting arrays of objects is involves some extra
    work, as we’ll see later…

VTC Academy        THSoft Co.,Ltd            10
Java Arrays
   Advantages
       Very efficient, quick to access and add to
       Type-safe, can only add items that match the declared type of
        the array
   Disadvantages
       Fixed size, some overhead in copying/resizing
       Can’t tell how many items in the array, just how large it was
        declared to be
       Limited functionality, need more general functionality


VTC Academy             THSoft Co.,Ltd                11
Java Collections
   What are they?
       A number of pre-packaged implementations of common
        ‘container’ classes, such as LinkedLists, Sets, etc.
       Part of the java.util package.
   Advantages
       Very flexible, can hold any kind of object
   Disadvantages
       Not as efficient as arrays (for some uses)
       Not type-safe. Store references to Object


VTC Academy             THSoft Co.,Ltd               12
Java Collections
   Two Types of Containers
   Collections
       Group of objects, which may restricted or manipulated in
        some way
       E.g. an ordered to make a List or LinkedList
       E.g. a Set, an unordered group which can only contain one of
        each item
   Maps
       Associative array, Dictionary, Lookup Table, Hash
       A group of name-value pairs

VTC Academy            THSoft Co.,Ltd               13
Java Collections




VTC Academy     THSoft Co.,Ltd   14
Java Collections
   Several implementations associated with each of
    the basic interfaces
   Each has its own advantages/disadvantages
   Maps
       HashMap, SortedMap
   Lists
       ArrayList
   Sets
       HashSet, SortedSet
VTC Academy           THSoft Co.,Ltd   15
Java Collections – The Basics
   HashMap and ArrayList are most commonly
    encountered
   Usual object creation syntax
   Generally hold references to the interface and not the
    specific collection
       Can then process them generically

Li st <Obj ect > m yLi st = new Ar r ayLi st <Obj ect >( ) ;
Li st <Bi gDeci m > ot her Li st = new Ar r ayLi st <Bi gDeci m >( 5) ;
                 al                                            al
Map<St r i ng, St r i ng> m ap = new HashM
                           yM                   ap( ) ;
Set <Fl oat > t hi ngs = new HashSet <Fl oat >( ) ;


VTC Academy             THSoft Co.,Ltd                16
Java Collections – Adding Items
   For Collections, use add()
List myList = new ArrayList();
myList.add(“A String”);
myList.add(“Other String”);

   For Maps, use put()
Map myMap = new HashMap();
myMap.put(“google”, “http://www.google.com”);
mpMap.put(“yahoo”, “http://www.yahoo.com”);




VTC Academy        THSoft Co.,Ltd      17
Java Collections – Copying
   Very easy, just use addAll()

List myList = new ArrayList();
//assume we add items to the list

List otherList = new ArrayList();
myList.addAll(myList);




VTC Academy        THSoft Co.,Ltd   18
Collections – Getting Individual
                 Items
   Use get()
   Note that we have to cast the object to its original type.
   Collections…
String s = (String)myList.get(1); //get first element
String s2 = (String)myList.get(10); //get tenth element


   Maps…
String s = (String)myMap.get(“google”);
String s2 = (String)mpMap.get(“yahoo”);




VTC Academy          THSoft Co.,Ltd              19
Collections – Getting all items
   For Lists, we could use a for loop, and loop
    through the list to get() each item
   But this doesn’t work for Maps.
   To allow generic handling of collections, Java
    defines an object called an Iterator
       An object whose function is to walk through a
        Collection of objects and provide access to each
        object in sequence

VTC Academy          THSoft Co.,Ltd           20
Collections – Getting all items
   Get an iterator using the iterator()
    method
   Iterator objects have three methods:
     next() – gets the next item in the collection
     hasNext() – tests whether it has reached the end
     remove() – removes the item just returned

   Basic iterators only go forwards
       Lists objects have a ListIterator that can go forward
        and backward

VTC Academy           THSoft Co.,Ltd           21
Collections – Getting all items
   Simple example:
List myList = new ArrayList();
//we add items

Iterator iterator = myList.iterator();
while (iterator.hasNext())
{
  String s = (String)iterator.next();
  //do something with it
}



VTC Academy      THSoft Co.,Ltd          22
Collections – Other Functions
   The java.util.Collections class has many
    useful methods for working with collections
       min, max, sort, reverse, search, shuffle
   Virtually all require your objects to implement
    an extra interface, called Comparable




VTC Academy           THSoft Co.,Ltd               23
Collections – Comparable
    The Comparable interface labels objects that can be
     compared to one another.
        Allows sorting algorithms to be written to work on any
         kind of object
        so long as they support this interface
    Single method to implement
 public int compareTo(Object o);
  Returns
     A negative number of parameter is less than the object
     
    Zero if they’re equal
    A positive number if the parameter is greater than the
     object
VTC Academy          THSoft Co.,Ltd              24
Collections – Comparator
   Like Comparable, but is a stand-alone object used
    for comparing other objects
       Useful when you want to use your criteria, not that of the
        implementor of the object.
       Or altering the behaviour of a system
   Many of the methods in the Collections object all a
    Comparator to be specified
   Again has single method:
public int compare(Object obj1, Object obj2)



VTC Academy            THSoft Co.,Ltd                25
Action on class
   Teacher
     hauc2@yahoo.com
     0984380003
       https://play.google.com/store/search?q=thsoft+co&c=apps
   Captions
   Members



VTC Academy              THSoft Co.,Ltd                 26

Contenu connexe

Tendances (17)

Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Lecture20 vector
Lecture20 vectorLecture20 vector
Lecture20 vector
 
Function Java Vector class
Function Java Vector classFunction Java Vector class
Function Java Vector class
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian Dragos
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Java Wrapper Classes and I/O Mechanisms
Java Wrapper Classes and I/O MechanismsJava Wrapper Classes and I/O Mechanisms
Java Wrapper Classes and I/O Mechanisms
 
Generics
GenericsGenerics
Generics
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
 
Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
 

En vedette

Generic Programming &amp; Collection
Generic Programming &amp; CollectionGeneric Programming &amp; Collection
Generic Programming &amp; CollectionArya
 
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...Akhil Mittal
 
C#.net applied OOP - Batch 3
C#.net applied OOP - Batch 3C#.net applied OOP - Batch 3
C#.net applied OOP - Batch 3Md. Mahedee Hasan
 
C#, OOP introduction and examples
C#, OOP introduction and examplesC#, OOP introduction and examples
C#, OOP introduction and examplesagni_agbc
 
C# OOP Advanced Concepts
C# OOP Advanced ConceptsC# OOP Advanced Concepts
C# OOP Advanced Conceptsagni_agbc
 
Introduction to .net framework
Introduction to .net frameworkIntroduction to .net framework
Introduction to .net frameworkArun Prasad
 

En vedette (12)

Unusual C# - OOP
Unusual C# - OOPUnusual C# - OOP
Unusual C# - OOP
 
Generic Programming &amp; Collection
Generic Programming &amp; CollectionGeneric Programming &amp; Collection
Generic Programming &amp; Collection
 
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...
Diving in OOP (Day 3): Polymorphism and Inheritance (Dynamic Binding/Run Time...
 
C#.net applied OOP - Batch 3
C#.net applied OOP - Batch 3C#.net applied OOP - Batch 3
C#.net applied OOP - Batch 3
 
Introduction to TFS 2013
Introduction to TFS 2013Introduction to TFS 2013
Introduction to TFS 2013
 
C# oop
C#   oopC#   oop
C# oop
 
C#, OOP introduction and examples
C#, OOP introduction and examplesC#, OOP introduction and examples
C#, OOP introduction and examples
 
OOP Basics
OOP BasicsOOP Basics
OOP Basics
 
C# - Part 1
C# - Part 1C# - Part 1
C# - Part 1
 
MS SQL Server
MS SQL ServerMS SQL Server
MS SQL Server
 
C# OOP Advanced Concepts
C# OOP Advanced ConceptsC# OOP Advanced Concepts
C# OOP Advanced Concepts
 
Introduction to .net framework
Introduction to .net frameworkIntroduction to .net framework
Introduction to .net framework
 

Similaire à Collections and generic class

Similaire à Collections and generic class (20)

Comparable/ Comparator
Comparable/ ComparatorComparable/ Comparator
Comparable/ Comparator
 
Java mcq
Java mcqJava mcq
Java mcq
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Lec2
Lec2Lec2
Lec2
 
Introduction to Intermediate Java
Introduction to Intermediate JavaIntroduction to Intermediate Java
Introduction to Intermediate Java
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 
Lec2
Lec2Lec2
Lec2
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Collections
CollectionsCollections
Collections
 
Collections in java
Collections in javaCollections in java
Collections in java
 
Lecture 24
Lecture 24Lecture 24
Lecture 24
 
Interfaces .ppt
Interfaces .pptInterfaces .ppt
Interfaces .ppt
 
Interfaces.ppt
Interfaces.pptInterfaces.ppt
Interfaces.ppt
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
 
Java 103
Java 103Java 103
Java 103
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
 
Java Course 4: Exceptions & Collections
Java Course 4: Exceptions & CollectionsJava Course 4: Exceptions & Collections
Java Course 4: Exceptions & Collections
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 

Dernier (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 

Collections and generic class

  • 1. Introduction to Java 2 Programming Lecture 5 Array and Collections Ref: www.ldodds.com Edited by Hoàng Văn Hậu – VTC Academy – THSoft co.,ltd https://play.google.com/store/apps/developer?id=THSoft+Co.,Ltd
  • 2. Introduction  Course Objectives  Organization of the Book VTC Academy THSoft Co.,Ltd 2
  • 3. Course Objectives  Upon completing the course, you will understand  Create, compile, and run Java programs  Primitive data types  Java control flow  Methods  Arrays (for teaching Java in two semesters, this could be the end)  Object-oriented programming  Core Java classes (Swing, exception, internationalization, multithreading, multimedia, I/O, networking, Java Collections Framework) VTC Academy THSoft Co.,Ltd 3
  • 4. Course Objectives, cont.  You will be able to  Develop programs using Eclipse IDE  Write simple programs using primitive data types, control statements, methods, and arrays.  Create and use methods  Write interesting projects VTC Academy THSoft Co.,Ltd 4
  • 5. Session 05: GENERIC PROGRAMMING AND COLLECTIONS  Generic class  Arrays  Working with arrays  Java API support for arrays  Collection classes  Types of collection  Working with Collections VTC Academy THSoft Co.,Ltd 5
  • 6. Definition of a simple generic class class Pair <T> { public T first; public T second; public Pair (T f, T s) { first = f; second = s; } public Pair () { first = null; second = null; } }  you instantiate the generic class by substituting actual types for type variables, as: Pair <String>  you can think the result as a class with a constructor public Pair (String f, String s), etc . .  you can then use the instantiated generic class as it were a normal class (almost): Pair <String> pair = new Pair <String> ("1","2"); VTC Academy THSoft Co.,Ltd 6
  • 7. Multiple type parameters allowed  you can have multiple type parameters class Pair <T, U> { public T first; public U second; public Pair (T x, U y) { first = x; second = y; } public Pair () { first = null; second = null; } }  to instantiate: Pair <String, Number> VTC Academy THSoft Co.,Ltd 7
  • 8. How to use generic class Pair<String> k = new Pair<String>("abc", "xyz"); Pair<double> d = new Pair<T>();// error Pair<Double> d = new Pair<Double>(); System.out.println(k.getFirst() + k.second); Pair<String, Double> k = new Pair<String, Double>("xxxx", 10.8); System.out.println(k.first + k.second); Illustration on code VTC Academy THSoft Co.,Ltd 8
  • 9. Java Arrays – Copying  Don’t copy arrays “by hand” by looping over the array  The System class has an arrayCopy method to do this efficiently int array1[] = new int[10]; int array2[] = new int[10]; //assume we add items to array1 //copy array1 into array2 System.arrayCopy(array1, 0, array2, 0, 10); //copy last 5 elements in array1 into first 5 of array2 System.arrayCopy(array1, 5, array2, 0, 5); VTC Academy THSoft Co.,Ltd 9
  • 10. Java Arrays – Sorting  Again no need to do this “by hand”.  The java.util.Arrays class has methods to sort different kinds of arrays int myArray[] = new int[] {5, 4, 3, 2, 1}; java.util.Arrays.sort(myArray); //myArray now holds 1, 2, 3, 4, 5  Sorting arrays of objects is involves some extra work, as we’ll see later… VTC Academy THSoft Co.,Ltd 10
  • 11. Java Arrays  Advantages  Very efficient, quick to access and add to  Type-safe, can only add items that match the declared type of the array  Disadvantages  Fixed size, some overhead in copying/resizing  Can’t tell how many items in the array, just how large it was declared to be  Limited functionality, need more general functionality VTC Academy THSoft Co.,Ltd 11
  • 12. Java Collections  What are they?  A number of pre-packaged implementations of common ‘container’ classes, such as LinkedLists, Sets, etc.  Part of the java.util package.  Advantages  Very flexible, can hold any kind of object  Disadvantages  Not as efficient as arrays (for some uses)  Not type-safe. Store references to Object VTC Academy THSoft Co.,Ltd 12
  • 13. Java Collections  Two Types of Containers  Collections  Group of objects, which may restricted or manipulated in some way  E.g. an ordered to make a List or LinkedList  E.g. a Set, an unordered group which can only contain one of each item  Maps  Associative array, Dictionary, Lookup Table, Hash  A group of name-value pairs VTC Academy THSoft Co.,Ltd 13
  • 14. Java Collections VTC Academy THSoft Co.,Ltd 14
  • 15. Java Collections  Several implementations associated with each of the basic interfaces  Each has its own advantages/disadvantages  Maps  HashMap, SortedMap  Lists  ArrayList  Sets  HashSet, SortedSet VTC Academy THSoft Co.,Ltd 15
  • 16. Java Collections – The Basics  HashMap and ArrayList are most commonly encountered  Usual object creation syntax  Generally hold references to the interface and not the specific collection  Can then process them generically Li st <Obj ect > m yLi st = new Ar r ayLi st <Obj ect >( ) ; Li st <Bi gDeci m > ot her Li st = new Ar r ayLi st <Bi gDeci m >( 5) ; al al Map<St r i ng, St r i ng> m ap = new HashM yM ap( ) ; Set <Fl oat > t hi ngs = new HashSet <Fl oat >( ) ; VTC Academy THSoft Co.,Ltd 16
  • 17. Java Collections – Adding Items  For Collections, use add() List myList = new ArrayList(); myList.add(“A String”); myList.add(“Other String”);  For Maps, use put() Map myMap = new HashMap(); myMap.put(“google”, “http://www.google.com”); mpMap.put(“yahoo”, “http://www.yahoo.com”); VTC Academy THSoft Co.,Ltd 17
  • 18. Java Collections – Copying  Very easy, just use addAll() List myList = new ArrayList(); //assume we add items to the list List otherList = new ArrayList(); myList.addAll(myList); VTC Academy THSoft Co.,Ltd 18
  • 19. Collections – Getting Individual Items  Use get()  Note that we have to cast the object to its original type.  Collections… String s = (String)myList.get(1); //get first element String s2 = (String)myList.get(10); //get tenth element  Maps… String s = (String)myMap.get(“google”); String s2 = (String)mpMap.get(“yahoo”); VTC Academy THSoft Co.,Ltd 19
  • 20. Collections – Getting all items  For Lists, we could use a for loop, and loop through the list to get() each item  But this doesn’t work for Maps.  To allow generic handling of collections, Java defines an object called an Iterator  An object whose function is to walk through a Collection of objects and provide access to each object in sequence VTC Academy THSoft Co.,Ltd 20
  • 21. Collections – Getting all items  Get an iterator using the iterator() method  Iterator objects have three methods:  next() – gets the next item in the collection  hasNext() – tests whether it has reached the end  remove() – removes the item just returned  Basic iterators only go forwards  Lists objects have a ListIterator that can go forward and backward VTC Academy THSoft Co.,Ltd 21
  • 22. Collections – Getting all items  Simple example: List myList = new ArrayList(); //we add items Iterator iterator = myList.iterator(); while (iterator.hasNext()) { String s = (String)iterator.next(); //do something with it } VTC Academy THSoft Co.,Ltd 22
  • 23. Collections – Other Functions  The java.util.Collections class has many useful methods for working with collections  min, max, sort, reverse, search, shuffle  Virtually all require your objects to implement an extra interface, called Comparable VTC Academy THSoft Co.,Ltd 23
  • 24. Collections – Comparable  The Comparable interface labels objects that can be compared to one another.  Allows sorting algorithms to be written to work on any kind of object  so long as they support this interface  Single method to implement public int compareTo(Object o);  Returns A negative number of parameter is less than the object   Zero if they’re equal  A positive number if the parameter is greater than the object VTC Academy THSoft Co.,Ltd 24
  • 25. Collections – Comparator  Like Comparable, but is a stand-alone object used for comparing other objects  Useful when you want to use your criteria, not that of the implementor of the object.  Or altering the behaviour of a system  Many of the methods in the Collections object all a Comparator to be specified  Again has single method: public int compare(Object obj1, Object obj2) VTC Academy THSoft Co.,Ltd 25
  • 26. Action on class  Teacher  hauc2@yahoo.com  0984380003  https://play.google.com/store/search?q=thsoft+co&c=apps  Captions  Members VTC Academy THSoft Co.,Ltd 26