SlideShare a Scribd company logo
www.webstackacademy.com
Java Programming Language SE – 6
Module 9:Collections and Generics Framework
www.webstackacademy.com
Objectives
● Describe the Collections
● Describe the general purpose implementations of the core interfaces in the
Collections framework
● Examine the Map interface
● Examine the legacy collection classes
● Create natural and custom ordering by implementing the Comparable and
Comparator interfaces
● Use generic collections
● Use type parameters in generic classes
● Refactor existing non-generic code
● Write a program to iterate over a collection
● Examine the enhanced for loop
www.webstackacademy.com
The Collections API
● A collection is a single object managing a group of objects known as
its elements.
● The Collections API contains interfaces that group objects as one of
the following:
● Collection – A group of objects called elements; implementations
determine whether there is specific ordering and whether duplicates
are permitted.
● Set – An unordered collection; no duplicates are permitted.
● List – An ordered collection; duplicates are permitted.
www.webstackacademy.com
The Collections API
www.webstackacademy.com
Collection Implementations
● There are several general purpose implementations of the core
interfaces (Set, List, Deque and Map)
www.webstackacademy.com
A Set Example
import java.util.*;
public class SetExample {
public static void main(String[] args) {
Set set = new HashSet();
set.add("one");
set.add("second");
set.add("3rd");
set.add(new Integer(4));
set.add(new Float(5.0F));
// duplicate, not added
set.add("second");// duplicate, not added
set.add(new Integer(4)); // duplicate, not added
System.out.println(set);
}
www.webstackacademy.com
A Set Example
The output generated from this program is:
[one, second, 5.0, 3rd, 4]
www.webstackacademy.com
A List Example
import java.util.*
public class ListExample {
public static void main(String[] args) {
List list = new ArrayList();
list.add("one");
list.add("second");
list.add("3rd");
list.add(new Integer(4));
list.add(new Float(5.0F));
// duplicate, is added
list.add("second");//duplicate, is added
list.add(new Integer(4)); // duplicate, is added
System.out.println(list);
}}
www.webstackacademy.com
A List Example
● The output generated from this program is:
● [one, second, 3rd, 4, 5.0, second, 4]
www.webstackacademy.com
The Map Interface
● Maps are sometimes called associative arrays
● A Map object describes mappings from keys to values:
● Duplicate keys are not allowed
● One-to-many mappings from keys to values is not permitted
www.webstackacademy.com
The Map Interface
● The contents of the Map interface can be viewed and manipulated as
collections
● entrySet – Returns a Set of all the key-value pairs.
● keySet – Returns a Set of all the keys in the map.
● values – Returns a Collection of all values in the map
www.webstackacademy.com
The Map Interface API
www.webstackacademy.com
A Map Example
public static void main(String args[]) {
Map map = new HashMap();
map.put("one","1st");
map.put("second", new Integer(2));
map.put("third","3rd");
map.put("third","III");
Set set1 = map.keySet();
Collection collection = map.values();
Set set2 = map.entrySet();
System.out.println(set1 + "n" + collection + "n" + set2);
}
www.webstackacademy.com
A Map Example
Output generated from the MapExample program:
[second, one, third]
[2, 1st, III]
[second=2, one=1st, third=III]
www.webstackacademy.com
Legacy Collection Classes
Collections in the JDK include:
● The Vector class, which implements the List interface.
● The Stack class, which is a subclass of the Vector class and supports
the push, pop, and peek methods.
● The Hashtable class, which implements the Map interface.
● The Properties class is an extension of Hashtable that only uses
Strings for keys and values.
● Each of these collections has an elements method that returns an
Enumeration object. The Enumeration interface is incompatible with,
the Iterator interface.
www.webstackacademy.com
Ordering Collections
The Comparable and Comparator interfaces are useful for ordering
collections:
● The Comparable interface imparts natural ordering to classes that
implement it.
● The Comparator interface specifies order relation. It can also be used
to override natural ordering.
● Both interfaces are useful for sorting collections.
www.webstackacademy.com
The Comparable Interface
Imparts natural ordering to classes that implement it:
● Used for sorting
● The compareTo method should be implemented to make any class
comparable:
● int compareTo(Object o) method
● The String, Date, and Integer classes implement the Comparable
interface
● You can sort the List elements containing objects that implement the
Comparable interface
www.webstackacademy.com
The Comparable Interface
● While sorting, the List elements follow the natural ordering of the
element types
– String elements – Alphabetical order
– Date elements – Chronological order
– Integer elements – Numerical order
www.webstackacademy.com
Example of the
Comparable Interface
class Student implements Comparable {
String firstName, lastName;
int studentID=0;
double GPA=0.0;
public Student(String firstName, String lastName, int studentID,
double GPA) {
if (firstName == null || lastName == null || studentID == 0
|| GPA == 0.0) {throw new IllegalArgumentException();}
this.firstName = firstName;
this.lastName = lastName;
this.studentID = studentID;
this.GPA = GPA;
}
www.webstackacademy.com
Example of the
Comparable Interface
public String firstName() { return firstName; }
public String lastName() { return lastName; }
public int studentID() { return studentID; }
public double GPA() { return GPA; }
public int compareTo(Object o) {
double f = GPA-((Student)o).GPA;
if (f == 0.0)
return 0;
else if (f<0.0)
return -1;
else
return 1;
}}
www.webstackacademy.com
Example of the
Comparable Interface
public static void main(String[] args) {
TreeSet studentSet = new TreeSet();
studentSet.add(new Student("Mike", "Hauffmann",101,4.0));
studentSet.add(new Student("John", "Lynn",102,2.8 ));
studentSet.add(new Student("Jim", "Max",103, 3.6));
studentSet.add(new Student("Kelly", "Grant",104,2.3));
Object[] studentArray = studentSet.toArray();
Student s;
for(Object obj : studentArray){
s = (Student) obj;
System.out.printf("Name = %s %s ID = %d GPA = %.1fn",
s.firstName(), s.lastName(), s.studentID(), s.GPA());
}}
www.webstackacademy.com
Example of the
Comparable Interface
Generated Output:
Name = Kelly Grant ID = 104 GPA = 2.3
Name = John Lynn ID = 102 GPA = 2.8
Name = Jim Max ID = 103 GPA = 3.6
Name = Mike Hauffmann ID = 101 GPA = 4.0
www.webstackacademy.com
The Comparator Interface
● Represents an order relation
● Used for sorting
● Enables sorting in an order different from the natural order
● Used for objects that do not implement the Comparable interface
● Can be passed to a sort method
● You need the compare method to implement the Comparator
interface:
– int compare(Object o1, Object o2) method
www.webstackacademy.com
Example of the
Comparator Interface
class Student {
String firstName, lastName;
int studentID=0; double GPA=0.0;
public Student(String firstName, String lastName,
int studentID, double GPA) {
if (firstName == null || lastName == null || studentID == 0 ||
GPA == 0.0) throw new NullPointerException();
this.firstName = firstName;this.lastName = lastName;this.studentID = studentID;
this.GPA = GPA;
}
public String firstName() { return firstName; }public String lastName() { return lastName; }
public int studentID() { return studentID; } public double GPA() { return GPA; }
}
www.webstackacademy.com
Example of the
Comparator Interface
public class NameComp implements Comparator {
public int compare(Object o1, Object o2) {
return
(((Student)o1).firstName.compareTo(((Student)o2).firstName));
}}
public class GradeComp implements Comparator {
public int compare(Object o1, Object o2) {
if (((Student)o1).GPA == ((Student)o2).GPA)
return 0;
else if (((Student)o1).GPA < ((Student)o2).GPA)
return -1;
else
return 1;
}}
www.webstackacademy.com
Example of the
Comparator Interface
public class ComparatorTest {
public static void main(String[] args) {
Comparator c = new NameComp();
TreeSet studentSet = new TreeSet(c);
studentSet.add(new Student("Mike", "Hauffmann",101,4.0));
studentSet.add(new Student("John", "Lynn",102,2.8 ));
studentSet.add(new Student("Jim", "Max",103, 3.6));
studentSet.add(new Student("Kelly", "Grant",104,2.3));
Object[] studentArray = studentSet.toArray();
Student s;
for(Object obj : studentArray) {
s = (Student) obj;
System.out.println("Name = %s %s ID = %d GPA = %.1fn",
s.firstName(), s.lastName(), s.studentID(), s.GPA());
}}
www.webstackacademy.com
Example of the
Comparator Interface
The output:
Name =Jim Max ID = 0 GPA = 3.6
Name = John Lynn ID = 0 GPA = 2.8
Name = Kelly Grant ID = 0 GPA = 2.3
Name = Mike Hauffmann ID = 0 GPA = 4.0
www.webstackacademy.com
Generics
Generics are described as follows:
● Provide compile-time type safety
● Eliminate the need for casts
● Provide the ability to create compiler-checked homogeneous
collections
www.webstackacademy.com
Generics
● Using non-generic collections:
ArrayList list = new ArrayList();
list.add(0, new Integer(42));
int total = ((Integer)list.get(0)).intValue();
● Using generic collections:
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(0, new Integer(42));
int total = list.get(0).intValue();
www.webstackacademy.com
Generic Set Example
import java.util.*;
public class GenSetExample {
public static void main(String[] args) {
Set<String> set = new HashSet<String>();
set.add("one");
set.add("second");
set.add("3rd");
set.add(new Integer(4));
set.add("second");
System.out.println(set);
}}
www.webstackacademy.com
Generic Map Example
public class MapPlayerRepository {
HashMap<String, String> players;
public MapPlayerRepository() {
players = new HashMap<String, String> ();
}
public String get(String position) {
String player = players.get(position);
return player;
}
public void put(String position, String name) {
players.put(position, name);
}
www.webstackacademy.com
Generics: Examining
Type Parameters
www.webstackacademy.com
Generic Collections API
www.webstackacademy.com
Wild Card Type Parameters
www.webstackacademy.com
The Type-Safety Guarantee
public class TestTypeSafety {
public static void main(String[] args) {
List<CheckingAccount> lc = new ArrayList<CheckingAccount>();
lc.add(new CheckingAccount("Fred")); // OK
lc.add(new SavingsAccount("Fred")); // Compile error!
CheckingAccount ca = lc.get(0);
}
}
www.webstackacademy.com
The Invariance Challenge
List<Account> la;
List<CheckingAccount> lc = new
ArrayList<CheckingAccount>();
List<SavingsAccount> ls = new ArrayList<SavingsAccount>();
la = lc;
la.add(new CheckingAccount("Fred"));
la = ls;
la.add(new CheckingAccount("Fred"));
SavingsAccount sa = ls.get(0); //aarrgghh!!
www.webstackacademy.com
The Invariance Challenge
In fact, la=lc; is illegal, so even though a CheckingAccount
is an Account, an ArrayList<CheckingAccount> is not an
ArrayList<Account>.
www.webstackacademy.com
The Covariance Response
public static void printNames(List <? extends Account> lea) {
for (int i=0; i < lea.size(); i++) {
System.out.println(lea.get(i).getName());
}
}
public static void main(String[] args) {
List<CheckingAccount> lc = new ArrayList<CheckingAccount>();
List<SavingsAccount> ls = new ArrayList<SavingsAccount>();
printNames(lc);
printNames(ls);
List<? extends Object> leo = lc; //OK
leo.add(new CheckingAccount("Fred"));//Compile error!
}}
www.webstackacademy.com
Generics: Refactoring
Existing Non-Generic Code
import java.util.*;
public class GenericsWarning {
public static void main(String[] args) {
List list = new ArrayList();
list.add(0, new Integer(42));
int total = ((Integer)list.get(0).intValue();
}}
www.webstackacademy.com
Generics: Refactoring
Existing Non-Generic Code
● javac GenericsWarning.java
Note: GenericsWarning.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
● javac -Xlint:unchecked GenericsWarning.java
GenericsWarning.java:7: warning: [unchecked] unchecked call to
add(int,E) as a member of the raw type java.util.ArrayList
list.add(0, new Integer(42));
1 warning
www.webstackacademy.com
Iterators
● Iteration is the process of retrieving every element in a collection.
● The basic Iterator interface allows you to scan forward through any
collection.
● A List object supports the ListIterator, which allows you to scan the list
backwards and insert or modify elements.
www.webstackacademy.com
Iterators
List<Student> list = new ArrayList<Student>();
// add some elements
Iterator<Student> elements = list.iterator();
while (elements.hasNext()) {
System.out.println(elements.next());
}
www.webstackacademy.com
Generic Iterator Interfaces
www.webstackacademy.com
The Enhanced for Loop
● The enhanced for loop has the following characteristics:
– Simplified iteration over collections
– Much shorter, clearer, and safer
– Effective for arrays
– Simpler when using nested loops
– Iterator disadvantages removed
● Iterators are error prone:
– Iterator variables occur three times per loop.
– This provides the opportunity for code to go wrong.
www.webstackacademy.com
The Enhanced for Loop
An enhanced for loop can look like the following:
● Using the iterator with a traditional for loop:
public void deleteAll(Collection<NameList> c){
for ( Iterator<NameList> i = c.iterator() ; i.hasNext() ; ){
NameList nl = i.next();
nl.deleteItem();
}}
www.webstackacademy.com
The Enhanced for Loop
● Iterating using an enhanced for loop in collections:
public void deleteAll(Collection<NameList> c){
for ( NameList nl : c ){
nl.deleteItem();
}}
www.webstackacademy.com
The Enhanced for Loop
● Nested enhanced for loops:
List<Subject> subjects=...;
List<Teacher> teachers=...;
List<Course> courseList = ArrayList<Course)();
for (Subject subj: subjects) {
for (Teacher tchr: teachers) {
courseList.add(new Course(subj, tchr));
}}
www.webstackacademy.com
Web Stack Academy (P) Ltd
#83, Farah Towers,
1st floor,MG Road,
Bangalore – 560001
M: +91-80-4128 9576
T: +91-98862 69112
E: info@www.webstackacademy.com
Ad

More Related Content

What's hot (19)

Java Collections API
Java Collections APIJava Collections API
Java Collections API
Alex Miller
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Edureka!
 
Advanced R cheat sheet
Advanced R cheat sheetAdvanced R cheat sheet
Advanced R cheat sheet
Dr. Volkan OBAN
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
Shalabh Chaudhary
 
Java Collections
Java  Collections Java  Collections
Java Collections
Kongu Engineering College, Perundurai, Erode
 
07 java collection
07 java collection07 java collection
07 java collection
Abhishek Khune
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
Drishti Bhalla
 
Java - Collections framework
Java - Collections frameworkJava - Collections framework
Java - Collections framework
Riccardo Cardin
 
Collections Java e Google Collections
Collections Java e Google CollectionsCollections Java e Google Collections
Collections Java e Google Collections
André Faria Gomes
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
Prof. Erwin Globio
 
Java collections
Java collectionsJava collections
Java collections
Amar Kutwal
 
Java collections
Java collectionsJava collections
Java collections
Hamid Ghorbani
 
Java Collection Framework
Java Collection FrameworkJava Collection Framework
Java Collection Framework
Lakshmi R
 
Java8.part2
Java8.part2Java8.part2
Java8.part2
Ivan Ivanov
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
Hitesh-Java
 
Generics
GenericsGenerics
Generics
Kongu Engineering College, Perundurai, Erode
 
Java 8 lambda expressions
Java 8 lambda expressionsJava 8 lambda expressions
Java 8 lambda expressions
Logan Chien
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
MANOJ KUMAR
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 

Similar to Core Java Programming Language (JSE) : Chapter IX - Collections and Generic Framework (20)

Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
Pramod Kumar
 
Module-1 Updated Collection Framework.pptx
Module-1 Updated Collection Framework.pptxModule-1 Updated Collection Framework.pptx
Module-1 Updated Collection Framework.pptx
rekhakeerti19
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
Sharon Rozinsky
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
Ganesh Samarthyam
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Hyderabad Scalability Meetup
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
Sanjoy Kumar Roy
 
Structural pattern 3
Structural pattern 3Structural pattern 3
Structural pattern 3
Naga Muruga
 
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
Sergii Maliarov
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android Programming
Purvik Rana
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
Van Huong
 
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
CPD INDIA
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
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
Raffi Khatchadourian
 
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
New York City College of Technology Computer Systems Technology Colloquium
 
Collections
CollectionsCollections
Collections
sagsharma
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
TechMagic
 
java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
BruceLee275640
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
Марія Русин
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
Alf Kristian Støyle
 
java tutorial 3
 java tutorial 3 java tutorial 3
java tutorial 3
Tushar Desarda
 
Ad

More from WebStackAcademy (20)

Webstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement JourneyWebstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement Journey
WebStackAcademy
 
WSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per SecondWSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per Second
WebStackAcademy
 
WSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer CourseWSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer Course
WebStackAcademy
 
Career Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and OpportunitiesCareer Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and Opportunities
WebStackAcademy
 
Webstack Academy - Internship Kick Off
Webstack Academy - Internship Kick OffWebstack Academy - Internship Kick Off
Webstack Academy - Internship Kick Off
WebStackAcademy
 
Building Your Online Portfolio
Building Your Online PortfolioBuilding Your Online Portfolio
Building Your Online Portfolio
WebStackAcademy
 
Front-End Developer's Career Roadmap
Front-End Developer's Career RoadmapFront-End Developer's Career Roadmap
Front-End Developer's Career Roadmap
WebStackAcademy
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
Angular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase IntegrationAngular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase Integration
WebStackAcademy
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
WebStackAcademy
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
WebStackAcademy
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - Introduction
WebStackAcademy
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
JavaScript - Chapter 15 - Debugging Techniques
 JavaScript - Chapter 15 - Debugging Techniques JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 15 - Debugging Techniques
WebStackAcademy
 
JavaScript - Chapter 14 - Form Handling
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Webstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement JourneyWebstack Academy - Course Demo Webinar and Placement Journey
Webstack Academy - Course Demo Webinar and Placement Journey
WebStackAcademy
 
WSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per SecondWSA: Scaling Web Service to Handle Millions of Requests per Second
WSA: Scaling Web Service to Handle Millions of Requests per Second
WebStackAcademy
 
WSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer CourseWSA: Course Demo Webinar - Full Stack Developer Course
WSA: Course Demo Webinar - Full Stack Developer Course
WebStackAcademy
 
Career Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and OpportunitiesCareer Building in AI - Technologies, Trends and Opportunities
Career Building in AI - Technologies, Trends and Opportunities
WebStackAcademy
 
Webstack Academy - Internship Kick Off
Webstack Academy - Internship Kick OffWebstack Academy - Internship Kick Off
Webstack Academy - Internship Kick Off
WebStackAcademy
 
Building Your Online Portfolio
Building Your Online PortfolioBuilding Your Online Portfolio
Building Your Online Portfolio
WebStackAcademy
 
Front-End Developer's Career Roadmap
Front-End Developer's Career RoadmapFront-End Developer's Career Roadmap
Front-End Developer's Career Roadmap
WebStackAcademy
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and Authorization
WebStackAcademy
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
WebStackAcademy
 
Angular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase IntegrationAngular - Chapter 6 - Firebase Integration
Angular - Chapter 6 - Firebase Integration
WebStackAcademy
 
Angular - Chapter 5 - Directives
 Angular - Chapter 5 - Directives Angular - Chapter 5 - Directives
Angular - Chapter 5 - Directives
WebStackAcademy
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
WebStackAcademy
 
Angular - Chapter 3 - Components
Angular - Chapter 3 - ComponentsAngular - Chapter 3 - Components
Angular - Chapter 3 - Components
WebStackAcademy
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
WebStackAcademy
 
Angular - Chapter 1 - Introduction
 Angular - Chapter 1 - Introduction Angular - Chapter 1 - Introduction
Angular - Chapter 1 - Introduction
WebStackAcademy
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
JavaScript - Chapter 15 - Debugging Techniques
 JavaScript - Chapter 15 - Debugging Techniques JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 15 - Debugging Techniques
WebStackAcademy
 
JavaScript - Chapter 14 - Form Handling
 JavaScript - Chapter 14 - Form Handling   JavaScript - Chapter 14 - Form Handling
JavaScript - Chapter 14 - Form Handling
WebStackAcademy
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)JavaScript - Chapter 13 - Browser Object Model(BOM)
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Ad

Recently uploaded (20)

Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptxWebinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
MSP360
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
Build With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdfBuild With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdf
Google Developer Group - Harare
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
The Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdfThe Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdf
Precisely
 
AI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdfAI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdf
Precisely
 
Does Pornify Allow NSFW? Everything You Should Know
Does Pornify Allow NSFW? Everything You Should KnowDoes Pornify Allow NSFW? Everything You Should Know
Does Pornify Allow NSFW? Everything You Should Know
Pornify CC
 
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of ExchangesJignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah Innovator
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
BookNet Canada
 
Financial Services Technology Summit 2025
Financial Services Technology Summit 2025Financial Services Technology Summit 2025
Financial Services Technology Summit 2025
Ray Bugg
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptxWebinar - Top 5 Backup Mistakes MSPs and Businesses Make   .pptx
Webinar - Top 5 Backup Mistakes MSPs and Businesses Make .pptx
MSP360
 
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Hybridize Functions: A Tool for Automatically Refactoring Imperative Deep Lea...
Raffi Khatchadourian
 
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
The No-Code Way to Build a Marketing Team with One AI Agent (Download the n8n...
SOFTTECHHUB
 
Cybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and MitigationCybersecurity Threat Vectors and Mitigation
Cybersecurity Threat Vectors and Mitigation
VICTOR MAESTRE RAMIREZ
 
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Integrating FME with Python: Tips, Demos, and Best Practices for Powerful Aut...
Safe Software
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)Design pattern talk by Kaya Weers - 2025 (v2)
Design pattern talk by Kaya Weers - 2025 (v2)
Kaya Weers
 
The Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdfThe Changing Compliance Landscape in 2025.pdf
The Changing Compliance Landscape in 2025.pdf
Precisely
 
AI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdfAI You Can Trust: The Critical Role of Governance and Quality.pdf
AI You Can Trust: The Critical Role of Governance and Quality.pdf
Precisely
 
Does Pornify Allow NSFW? Everything You Should Know
Does Pornify Allow NSFW? Everything You Should KnowDoes Pornify Allow NSFW? Everything You Should Know
Does Pornify Allow NSFW? Everything You Should Know
Pornify CC
 
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of ExchangesJignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah - The Innovator and Czar of Exchanges
Jignesh Shah Innovator
 
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Challenges in Migrating Imperative Deep Learning Programs to Graph Execution:...
Raffi Khatchadourian
 
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...Canadian book publishing: Insights from the latest salary survey - Tech Forum...
Canadian book publishing: Insights from the latest salary survey - Tech Forum...
BookNet Canada
 
Financial Services Technology Summit 2025
Financial Services Technology Summit 2025Financial Services Technology Summit 2025
Financial Services Technology Summit 2025
Ray Bugg
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à GenèveUiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPath Automation Suite – Cas d'usage d'une NGO internationale basée à Genève
UiPathCommunity
 

Core Java Programming Language (JSE) : Chapter IX - Collections and Generic Framework

  • 1. www.webstackacademy.com Java Programming Language SE – 6 Module 9:Collections and Generics Framework
  • 2. www.webstackacademy.com Objectives ● Describe the Collections ● Describe the general purpose implementations of the core interfaces in the Collections framework ● Examine the Map interface ● Examine the legacy collection classes ● Create natural and custom ordering by implementing the Comparable and Comparator interfaces ● Use generic collections ● Use type parameters in generic classes ● Refactor existing non-generic code ● Write a program to iterate over a collection ● Examine the enhanced for loop
  • 3. www.webstackacademy.com The Collections API ● A collection is a single object managing a group of objects known as its elements. ● The Collections API contains interfaces that group objects as one of the following: ● Collection – A group of objects called elements; implementations determine whether there is specific ordering and whether duplicates are permitted. ● Set – An unordered collection; no duplicates are permitted. ● List – An ordered collection; duplicates are permitted.
  • 5. www.webstackacademy.com Collection Implementations ● There are several general purpose implementations of the core interfaces (Set, List, Deque and Map)
  • 6. www.webstackacademy.com A Set Example import java.util.*; public class SetExample { public static void main(String[] args) { Set set = new HashSet(); set.add("one"); set.add("second"); set.add("3rd"); set.add(new Integer(4)); set.add(new Float(5.0F)); // duplicate, not added set.add("second");// duplicate, not added set.add(new Integer(4)); // duplicate, not added System.out.println(set); }
  • 7. www.webstackacademy.com A Set Example The output generated from this program is: [one, second, 5.0, 3rd, 4]
  • 8. www.webstackacademy.com A List Example import java.util.* public class ListExample { public static void main(String[] args) { List list = new ArrayList(); list.add("one"); list.add("second"); list.add("3rd"); list.add(new Integer(4)); list.add(new Float(5.0F)); // duplicate, is added list.add("second");//duplicate, is added list.add(new Integer(4)); // duplicate, is added System.out.println(list); }}
  • 9. www.webstackacademy.com A List Example ● The output generated from this program is: ● [one, second, 3rd, 4, 5.0, second, 4]
  • 10. www.webstackacademy.com The Map Interface ● Maps are sometimes called associative arrays ● A Map object describes mappings from keys to values: ● Duplicate keys are not allowed ● One-to-many mappings from keys to values is not permitted
  • 11. www.webstackacademy.com The Map Interface ● The contents of the Map interface can be viewed and manipulated as collections ● entrySet – Returns a Set of all the key-value pairs. ● keySet – Returns a Set of all the keys in the map. ● values – Returns a Collection of all values in the map
  • 13. www.webstackacademy.com A Map Example public static void main(String args[]) { Map map = new HashMap(); map.put("one","1st"); map.put("second", new Integer(2)); map.put("third","3rd"); map.put("third","III"); Set set1 = map.keySet(); Collection collection = map.values(); Set set2 = map.entrySet(); System.out.println(set1 + "n" + collection + "n" + set2); }
  • 14. www.webstackacademy.com A Map Example Output generated from the MapExample program: [second, one, third] [2, 1st, III] [second=2, one=1st, third=III]
  • 15. www.webstackacademy.com Legacy Collection Classes Collections in the JDK include: ● The Vector class, which implements the List interface. ● The Stack class, which is a subclass of the Vector class and supports the push, pop, and peek methods. ● The Hashtable class, which implements the Map interface. ● The Properties class is an extension of Hashtable that only uses Strings for keys and values. ● Each of these collections has an elements method that returns an Enumeration object. The Enumeration interface is incompatible with, the Iterator interface.
  • 16. www.webstackacademy.com Ordering Collections The Comparable and Comparator interfaces are useful for ordering collections: ● The Comparable interface imparts natural ordering to classes that implement it. ● The Comparator interface specifies order relation. It can also be used to override natural ordering. ● Both interfaces are useful for sorting collections.
  • 17. www.webstackacademy.com The Comparable Interface Imparts natural ordering to classes that implement it: ● Used for sorting ● The compareTo method should be implemented to make any class comparable: ● int compareTo(Object o) method ● The String, Date, and Integer classes implement the Comparable interface ● You can sort the List elements containing objects that implement the Comparable interface
  • 18. www.webstackacademy.com The Comparable Interface ● While sorting, the List elements follow the natural ordering of the element types – String elements – Alphabetical order – Date elements – Chronological order – Integer elements – Numerical order
  • 19. www.webstackacademy.com Example of the Comparable Interface class Student implements Comparable { String firstName, lastName; int studentID=0; double GPA=0.0; public Student(String firstName, String lastName, int studentID, double GPA) { if (firstName == null || lastName == null || studentID == 0 || GPA == 0.0) {throw new IllegalArgumentException();} this.firstName = firstName; this.lastName = lastName; this.studentID = studentID; this.GPA = GPA; }
  • 20. www.webstackacademy.com Example of the Comparable Interface public String firstName() { return firstName; } public String lastName() { return lastName; } public int studentID() { return studentID; } public double GPA() { return GPA; } public int compareTo(Object o) { double f = GPA-((Student)o).GPA; if (f == 0.0) return 0; else if (f<0.0) return -1; else return 1; }}
  • 21. www.webstackacademy.com Example of the Comparable Interface public static void main(String[] args) { TreeSet studentSet = new TreeSet(); studentSet.add(new Student("Mike", "Hauffmann",101,4.0)); studentSet.add(new Student("John", "Lynn",102,2.8 )); studentSet.add(new Student("Jim", "Max",103, 3.6)); studentSet.add(new Student("Kelly", "Grant",104,2.3)); Object[] studentArray = studentSet.toArray(); Student s; for(Object obj : studentArray){ s = (Student) obj; System.out.printf("Name = %s %s ID = %d GPA = %.1fn", s.firstName(), s.lastName(), s.studentID(), s.GPA()); }}
  • 22. www.webstackacademy.com Example of the Comparable Interface Generated Output: Name = Kelly Grant ID = 104 GPA = 2.3 Name = John Lynn ID = 102 GPA = 2.8 Name = Jim Max ID = 103 GPA = 3.6 Name = Mike Hauffmann ID = 101 GPA = 4.0
  • 23. www.webstackacademy.com The Comparator Interface ● Represents an order relation ● Used for sorting ● Enables sorting in an order different from the natural order ● Used for objects that do not implement the Comparable interface ● Can be passed to a sort method ● You need the compare method to implement the Comparator interface: – int compare(Object o1, Object o2) method
  • 24. www.webstackacademy.com Example of the Comparator Interface class Student { String firstName, lastName; int studentID=0; double GPA=0.0; public Student(String firstName, String lastName, int studentID, double GPA) { if (firstName == null || lastName == null || studentID == 0 || GPA == 0.0) throw new NullPointerException(); this.firstName = firstName;this.lastName = lastName;this.studentID = studentID; this.GPA = GPA; } public String firstName() { return firstName; }public String lastName() { return lastName; } public int studentID() { return studentID; } public double GPA() { return GPA; } }
  • 25. www.webstackacademy.com Example of the Comparator Interface public class NameComp implements Comparator { public int compare(Object o1, Object o2) { return (((Student)o1).firstName.compareTo(((Student)o2).firstName)); }} public class GradeComp implements Comparator { public int compare(Object o1, Object o2) { if (((Student)o1).GPA == ((Student)o2).GPA) return 0; else if (((Student)o1).GPA < ((Student)o2).GPA) return -1; else return 1; }}
  • 26. www.webstackacademy.com Example of the Comparator Interface public class ComparatorTest { public static void main(String[] args) { Comparator c = new NameComp(); TreeSet studentSet = new TreeSet(c); studentSet.add(new Student("Mike", "Hauffmann",101,4.0)); studentSet.add(new Student("John", "Lynn",102,2.8 )); studentSet.add(new Student("Jim", "Max",103, 3.6)); studentSet.add(new Student("Kelly", "Grant",104,2.3)); Object[] studentArray = studentSet.toArray(); Student s; for(Object obj : studentArray) { s = (Student) obj; System.out.println("Name = %s %s ID = %d GPA = %.1fn", s.firstName(), s.lastName(), s.studentID(), s.GPA()); }}
  • 27. www.webstackacademy.com Example of the Comparator Interface The output: Name =Jim Max ID = 0 GPA = 3.6 Name = John Lynn ID = 0 GPA = 2.8 Name = Kelly Grant ID = 0 GPA = 2.3 Name = Mike Hauffmann ID = 0 GPA = 4.0
  • 28. www.webstackacademy.com Generics Generics are described as follows: ● Provide compile-time type safety ● Eliminate the need for casts ● Provide the ability to create compiler-checked homogeneous collections
  • 29. www.webstackacademy.com Generics ● Using non-generic collections: ArrayList list = new ArrayList(); list.add(0, new Integer(42)); int total = ((Integer)list.get(0)).intValue(); ● Using generic collections: ArrayList<Integer> list = new ArrayList<Integer>(); list.add(0, new Integer(42)); int total = list.get(0).intValue();
  • 30. www.webstackacademy.com Generic Set Example import java.util.*; public class GenSetExample { public static void main(String[] args) { Set<String> set = new HashSet<String>(); set.add("one"); set.add("second"); set.add("3rd"); set.add(new Integer(4)); set.add("second"); System.out.println(set); }}
  • 31. www.webstackacademy.com Generic Map Example public class MapPlayerRepository { HashMap<String, String> players; public MapPlayerRepository() { players = new HashMap<String, String> (); } public String get(String position) { String player = players.get(position); return player; } public void put(String position, String name) { players.put(position, name); }
  • 35. www.webstackacademy.com The Type-Safety Guarantee public class TestTypeSafety { public static void main(String[] args) { List<CheckingAccount> lc = new ArrayList<CheckingAccount>(); lc.add(new CheckingAccount("Fred")); // OK lc.add(new SavingsAccount("Fred")); // Compile error! CheckingAccount ca = lc.get(0); } }
  • 36. www.webstackacademy.com The Invariance Challenge List<Account> la; List<CheckingAccount> lc = new ArrayList<CheckingAccount>(); List<SavingsAccount> ls = new ArrayList<SavingsAccount>(); la = lc; la.add(new CheckingAccount("Fred")); la = ls; la.add(new CheckingAccount("Fred")); SavingsAccount sa = ls.get(0); //aarrgghh!!
  • 37. www.webstackacademy.com The Invariance Challenge In fact, la=lc; is illegal, so even though a CheckingAccount is an Account, an ArrayList<CheckingAccount> is not an ArrayList<Account>.
  • 38. www.webstackacademy.com The Covariance Response public static void printNames(List <? extends Account> lea) { for (int i=0; i < lea.size(); i++) { System.out.println(lea.get(i).getName()); } } public static void main(String[] args) { List<CheckingAccount> lc = new ArrayList<CheckingAccount>(); List<SavingsAccount> ls = new ArrayList<SavingsAccount>(); printNames(lc); printNames(ls); List<? extends Object> leo = lc; //OK leo.add(new CheckingAccount("Fred"));//Compile error! }}
  • 39. www.webstackacademy.com Generics: Refactoring Existing Non-Generic Code import java.util.*; public class GenericsWarning { public static void main(String[] args) { List list = new ArrayList(); list.add(0, new Integer(42)); int total = ((Integer)list.get(0).intValue(); }}
  • 40. www.webstackacademy.com Generics: Refactoring Existing Non-Generic Code ● javac GenericsWarning.java Note: GenericsWarning.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. ● javac -Xlint:unchecked GenericsWarning.java GenericsWarning.java:7: warning: [unchecked] unchecked call to add(int,E) as a member of the raw type java.util.ArrayList list.add(0, new Integer(42)); 1 warning
  • 41. www.webstackacademy.com Iterators ● Iteration is the process of retrieving every element in a collection. ● The basic Iterator interface allows you to scan forward through any collection. ● A List object supports the ListIterator, which allows you to scan the list backwards and insert or modify elements.
  • 42. www.webstackacademy.com Iterators List<Student> list = new ArrayList<Student>(); // add some elements Iterator<Student> elements = list.iterator(); while (elements.hasNext()) { System.out.println(elements.next()); }
  • 44. www.webstackacademy.com The Enhanced for Loop ● The enhanced for loop has the following characteristics: – Simplified iteration over collections – Much shorter, clearer, and safer – Effective for arrays – Simpler when using nested loops – Iterator disadvantages removed ● Iterators are error prone: – Iterator variables occur three times per loop. – This provides the opportunity for code to go wrong.
  • 45. www.webstackacademy.com The Enhanced for Loop An enhanced for loop can look like the following: ● Using the iterator with a traditional for loop: public void deleteAll(Collection<NameList> c){ for ( Iterator<NameList> i = c.iterator() ; i.hasNext() ; ){ NameList nl = i.next(); nl.deleteItem(); }}
  • 46. www.webstackacademy.com The Enhanced for Loop ● Iterating using an enhanced for loop in collections: public void deleteAll(Collection<NameList> c){ for ( NameList nl : c ){ nl.deleteItem(); }}
  • 47. www.webstackacademy.com The Enhanced for Loop ● Nested enhanced for loops: List<Subject> subjects=...; List<Teacher> teachers=...; List<Course> courseList = ArrayList<Course)(); for (Subject subj: subjects) { for (Teacher tchr: teachers) { courseList.add(new Course(subj, tchr)); }}
  • 48. www.webstackacademy.com Web Stack Academy (P) Ltd #83, Farah Towers, 1st floor,MG Road, Bangalore – 560001 M: +91-80-4128 9576 T: +91-98862 69112 E: info@www.webstackacademy.com
  翻译: