SlideShare a Scribd company logo
Java Programming -
Collection
Oum Saokosal
Master’s Degree in information systems,Jeonju
University,South Korea
012 252 752 / 070 252 752
oumsaokosal@gmail.com
Contact Me
• Tel: 012 252 752 / 070 252 752
• Email: oumsaokosal@gmail.com
• FB Page: https://facebook.com/kosalgeek
• PPT: http://www.slideshare.net/oumsaokosal
• YouTube: https://www.youtube.com/user/oumsaokosal
• Twitter: https://twitter.com/okosal
• Web: http://kosalgeek.com
3
Agenda
•Building arrays
•Vectors and Hashtables
•Data structures introduced in Java 2
•Using wrappers to convert primitive data
types to objects
•Handling exceptions
Ad
4
Arrays
• Accessingarrays
• Accessarraysby supplying the indexin square bracketsafter the
variable name,variableName[index]
• The first indexis0, not 1
• Example
• Here, the argument to main is an array of Strings called args
public class Test {
public static void main(String[] args) {
System.out.println("First argument: " + args[0]);
}
}
> javac Test.java
> java Test Hello There
First argument is Hello
5
The Array length Field
• Arrays have a built-in field called length that storesthe size of
the array
• The length is one bigger than the biggest index, due to the fact that
the index starts at 0
• Example
public class Test2 {
public static void main(String[] args) {
System.out.println("Number of args is " +
args.length);
}
}
> javac Test2.java
> java Test2
Number of args is 0
> java Test2 Hello There
Number of args is 2
Ad
6
Building Arrays
• Arrays can be built in a one-step or two-
step process
1. The one-step process is of the following form:
type[] var = { val1, val2, ... , valN };
• For example:
int[] values = { 10, 100, 1000 };
Point[] points = { new Point(0, 0),
new Point(1, 2), ...
};
7
Building Arrays, cont.
2. With the two-step process, first allocate
an array of references:
type[] var = new type[size];
• For example:
int[] values = new int[7];
Point[] points = new Point[length];
• Second, populate the array
points[0] = new Point(...);
points[1] = new Point(...);
...
Ad
8
Multidimensional Arrays
•Multidimensional arrays are implemented as
an arrayof arrays
int[][] twoD = new int[64][32];
String[][] cats = {
{ "Caesar", "blue-point" },
{ "Heather", "seal-point" },
{ "Ted" , "red-point" }
};
9
Data Structures
• Java 1.0 introduced two synchronized data
structures in the java.util package
• Vector
• A stretchable(resizable) array of Objects
• Time to accessan element is constant regardlessof
position
• Time to insert element is proportionalto the size of the
vector
• Hashtable
• Stores key-value pairs as Objects
• Neither thekeysor values can be null
• Time to access/insert is proportionaltothe size of the
hashtable
Ad
10
UsefulVector Methods
• addElement / insertElementAt / setElementAt
• Add elementsto the vector
• removeElement / removeElementAt
• Removesan element from the vector
• firstElement / lastElement
• Returnsa reference to the first and last element,respectively
(without removing)
• elementAt
• Returnsthe element at the specified index
• indexOf
• Returnsthe indexof an element that equals the object specified
• contains
• Determinesif the vector containsan object
11
UsefulVector Methods (cont)
• elements
• Returns an Enumerationof objects in the vector
Enumeration elements = vector.elements();
while(elements.hasMoreElements()) {
System.out.println(elements.nextElement());
}
• size
• The number of elements in the vector
• capacity
• The number of elements the vector can hold
before becoming resized
Ad
12
Useful Hashtable Methods
• put / get
• Stores or retrievesa value in the hashtable
• remove / clear
• Removesa particular entry or all entriesfrom the hashtable
• containsKey / contains
• Determinesif the hashtable containsa particular key or element
• keys / elements
• Returnsan enumeration ofall keysor elements,respectively
• size
• Returnsthe number of elementsin the hashtable
• rehash
• Increasesthe capacity ofthe hashtable and reorganizesit
13
Collections Framework
•Additional data structures
Collection
Set
SortedSet
List
ArrayList
LinkedList
Vector*
HashSet
TreeSet
Map
SortedMap
HashMap
Hashtable*
TreeMap
Interface Concrete class *Synchronized Access
Ad
14
Collection Interfaces
• Collection
• Abstract classfor holding groupsofobjects
• Set
• Group of objectscontainingno duplicates
• SortedSet
• Set of objects(no duplicates)stored in ascending order
• Order is determined by a Comparator
• List
• Physically (versus logically)ordered sequence ofobjects
• Map
• Stores objects(unordered)identified by unique keys
• SortedMap
• Objectsstored in ascending order based on their key value
• Neither duplicate or null keysare permitted
15
Collections Class
• Use to create synchronized data structures
List list = Collection.synchronizedList(new ArrayList());
Map map = Collections.synchronizedMap(new HashMap());
• Provides useful (static) utility methods
• sort
• Sorts (ascending) theelementsin thelist
• max, min
• Returns the maximum or minimum element in the collection
• reverse
• Reverses the order of theelements in the list
• shuffle
• Randomly permutes theorder of the elements
Ad
16
WrapperClasses
•Each primitive data type has a
corresponding object (wrapperclass)
Primitive Corresponding
Data Type Object Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
17
Wrapper Uses
• Defines useful constants for each data type
• For example,
Integer.MAX_VALUE
Float.NEGATIVE_INFINITY
• Convert between data types
• Use parseXxx method to convert a String to
the correspondingprimitivedata type
try {
String value = "3.14e6";
double d = Double.parseDouble(value);
} catch (NumberFormatException nfe) {
System.out.println("Can't convert: " + value);
}
Ad
18
Exception Hierarchy
•Simplified Diagram of Exception
Hierarchy
Throwable
Error
IOException RuntimeException
Exception
…
19
ThrowableTypes
• Error
• A non-recoverableproblem that should not be
caught (OutOfMemoryError,
StackOverflowError, …)
• Exception
• An abnormalcondition that should be caught and
handled by the programmer
• RuntimeException
• Special case; does not have to be caught
• Usually the result of a poorly written program
(integer division by zero, array out-of-bounds,etc.)
• A RuntimeException is considereda bug
Ad
20
Multiple CatchClauses
• A single try can have more that one catch clause
• If multiple catch clauses are used, order them from
the most specific to the most general
• If no appropriatecatch is found,the exception is
handedto any outer try blocks
• If no catch clause is found within the method, then the
exception is thrown by the method
try {
...
} catch (ExceptionType1 var1) {
// Do something
} catch (ExceptionType2 var2) {
// Do something else
}
21
Try-Catch, Example
...
BufferedReader in = null;
String lineIn;
try {
in = new BufferedReader(new FileReader("book.txt"));
while((lineIn = in.readLine()) != null) {
System.out.println(lineIn);
}
in.close();
} catch (FileNotFoundException fnfe ) {
System.out.println("File not found.");
} catch (EOFException eofe) {
System.out.println("Unexpected End of File.");
} catch (IOException ioe) {
System.out.println("IOError reading input: " + ioe);
ioe.printStackTrace(); // Show stack dump
}
Ad
22
The finally Clause
•After the final catch clause, an optional
finally clause may be defined
•The finally clause is always executed,
even if the try or catch blocks are
exited through a break, continue, or
return
try {
...
} catch (SomeException someVar) {
// Do something
} finally {
// Always executed
}
23
Thrown Exceptions
• If a potential exception is not handled in the
method, then the method must declare that
the exception can be thrown
public SomeType someMethod(...) throws SomeException {
// Unhandled potential exception
...
}
• Note: Multiple exception types (comma
separated) can be declared in the throws
clause
• Explicitly generating an exception
throw new IOException("Blocked by firewall.");
throw new MalformedURLException("Invalid protocol");
Ad
Ad

More Related Content

What's hot (20)

PDF
4 gouping object
87 slides393 views
PDF
Pavel kravchenko obj c runtime
24 slides510 views
PDF
Out ofmemoryerror what is the cost of java objects
44 slides2K views
PDF
Scala - en bedre og mere effektiv Java?
53 slides1.4K views
PDF
The Ring programming language version 1.7 book - Part 39 of 196
10 slides24 views
PPT
POLITEKNIK MALAYSIA
51 slides15 views
PPS
CS101- Introduction to Computing- Lecture 26
51 slides432 views
PPT
Xm lparsers
38 slides958 views
PDF
Clojure class
134 slides3K views
PPTX
Chap2 class,objects contd
49 slides248 views
PDF
Java Programming - 06 java file io
PDF
Spark workshop
61 slides1.1K views
PDF
The Ring programming language version 1.5.3 book - Part 83 of 184
10 slides11 views
PPTX
Java 101
77 slides1.1K views
PPTX
Procedural Content Generation with Clojure
35 slides1.7K views
PDF
The Ring programming language version 1.10 book - Part 39 of 212
10 slides11 views
PDF
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
13 slides700 views
PDF
The Ring programming language version 1.5.2 book - Part 70 of 181
10 slides11 views
PPTX
Clojure for Data Science
69 slides4.8K views
PPTX
Java 104
33 slides341 views
4 gouping object
87 slides393 views
Pavel kravchenko obj c runtime
24 slides510 views
Out ofmemoryerror what is the cost of java objects
44 slides2K views
Scala - en bedre og mere effektiv Java?
53 slides1.4K views
The Ring programming language version 1.7 book - Part 39 of 196
10 slides24 views
POLITEKNIK MALAYSIA
51 slides15 views
CS101- Introduction to Computing- Lecture 26
51 slides432 views
Xm lparsers
38 slides958 views
Clojure class
134 slides3K views
Chap2 class,objects contd
49 slides248 views
Java Programming - 06 java file io
Spark workshop
61 slides1.1K views
The Ring programming language version 1.5.3 book - Part 83 of 184
10 slides11 views
Java 101
77 slides1.1K views
Procedural Content Generation with Clojure
35 slides1.7K views
The Ring programming language version 1.10 book - Part 39 of 212
10 slides11 views
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
13 slides700 views
The Ring programming language version 1.5.2 book - Part 70 of 181
10 slides11 views
Clojure for Data Science
69 slides4.8K views
Java 104
33 slides341 views

Viewers also liked (20)

PDF
Java OOP Programming language (Part 6) - Abstract Class & Interface
18 slides1.5K views
PDF
Java OOP Programming language (Part 7) - Swing
30 slides1.1K views
PDF
Javascript & DOM - Part 1- Javascript Tutorial for Beginners with Examples
16 slides1.5K views
PDF
Java OOP Programming language (Part 5) - Inheritance
39 slides631 views
PPTX
Android app development - Java Programming for Android
5 slides864 views
PDF
Copy As Interface | Erika Hall | Web 2.0 Expo
130 slides14K views
PPTX
Java interface
12 slides4K views
PPT
Measuring And Defining The Experience Of Immersion In Games
30 slides1.9K views
PPT
Chapter 7 String
17 slides1.9K views
PPT
ITS (Intelligent Teleportation System)
11 slides1.9K views
PPT
Terminology In Telecommunication
20 slides2.2K views
PPT
Chapter 9 Interface
35 slides1.2K views
PPTX
Tutorial 1
56 slides300 views
PPT
Kimchi Questionnaire
18 slides2.5K views
PPT
Actionscript 3 - Session 7 Other Note
8 slides621 views
PPT
Java interface
16 slides2.5K views
PPT
Interface in java By Dheeraj Kumar Singh
25 slides5.9K views
PPT
Chapter 8 Inheritance
39 slides2.3K views
PPT
Rayleigh Fading Channel In Mobile Digital Communication System
10 slides10.3K views
PDF
Python - Lecture 1
20 slides1.3K views
Java OOP Programming language (Part 6) - Abstract Class & Interface
18 slides1.5K views
Java OOP Programming language (Part 7) - Swing
30 slides1.1K views
Javascript & DOM - Part 1- Javascript Tutorial for Beginners with Examples
16 slides1.5K views
Java OOP Programming language (Part 5) - Inheritance
39 slides631 views
Android app development - Java Programming for Android
5 slides864 views
Copy As Interface | Erika Hall | Web 2.0 Expo
130 slides14K views
Java interface
12 slides4K views
Measuring And Defining The Experience Of Immersion In Games
30 slides1.9K views
Chapter 7 String
17 slides1.9K views
ITS (Intelligent Teleportation System)
11 slides1.9K views
Terminology In Telecommunication
20 slides2.2K views
Chapter 9 Interface
35 slides1.2K views
Tutorial 1
56 slides300 views
Kimchi Questionnaire
18 slides2.5K views
Actionscript 3 - Session 7 Other Note
8 slides621 views
Java interface
16 slides2.5K views
Interface in java By Dheeraj Kumar Singh
25 slides5.9K views
Chapter 8 Inheritance
39 slides2.3K views
Rayleigh Fading Channel In Mobile Digital Communication System
10 slides10.3K views
Python - Lecture 1
20 slides1.3K views
Ad

Similar to Java OOP Programming language (Part 4) - Collection (20)

PPT
STRINGS IN JAVA
PPTX
Learning core java
42 slides1.1K views
PPT
description of Collections, seaching & Sorting
38 slides9 views
DOC
Advanced core java
119 slides2.6K views
PPTX
CH1 ARRAY (1).pptx
24 slides16 views
PPTX
Java Hands-On Workshop
59 slides498 views
DOCX
Jist of Java
13 slides249 views
DOCX
JAVA CONCEPTS AND PRACTICES
13 slides322 views
PPTX
Collections Training
30 slides594 views
PDF
Lecture 4 - Object Interaction and Collections
34 slides275 views
PDF
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
89 slides8.9K views
PPTX
Learn advanced java programming
32 slides1.4K views
PPTX
Arrays in programming
23 slides121 views
PPTX
Java introduction
61 slides757 views
PPTX
Java For Automation
44 slides157 views
PPTX
Object Oriented Programming unit 1 content for students
78 slides25 views
PPTX
Collection and framework
42 slides119 views
PPTX
Java Unit 2 (Part 2)
15 slides309 views
PPT
22.ppt
47 slides12 views
PPT
Presentation to java
56 slides152 views
STRINGS IN JAVA
Learning core java
42 slides1.1K views
description of Collections, seaching & Sorting
38 slides9 views
Advanced core java
119 slides2.6K views
CH1 ARRAY (1).pptx
24 slides16 views
Java Hands-On Workshop
59 slides498 views
Jist of Java
13 slides249 views
JAVA CONCEPTS AND PRACTICES
13 slides322 views
Collections Training
30 slides594 views
Lecture 4 - Object Interaction and Collections
34 slides275 views
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
89 slides8.9K views
Learn advanced java programming
32 slides1.4K views
Arrays in programming
23 slides121 views
Java introduction
61 slides757 views
Java For Automation
44 slides157 views
Object Oriented Programming unit 1 content for students
78 slides25 views
Collection and framework
42 slides119 views
Java Unit 2 (Part 2)
15 slides309 views
22.ppt
47 slides12 views
Presentation to java
56 slides152 views
Ad

More from OUM SAOKOSAL (20)

PPTX
Class Diagram | OOP and Design Patterns by Oum Saokosal
15 slides1.1K views
PDF
Java OOP Programming language (Part 1) - Introduction to Java
14 slides669 views
PDF
Aggregate rank bringing order to web sites
8 slides649 views
DOC
How to succeed in graduate school
26 slides1.1K views
PDF
Google
20 slides812 views
PDF
E miner
132 slides1.7K views
PDF
Data preparation for mining world wide web browsing patterns (1999)
27 slides4.1K views
PDF
Consumer acceptance of online banking an extension of the technology accepta...
12 slides5.5K views
DOCX
When Do People Help
2 slides417 views
DOC
Mc Nemar
5 slides5.9K views
DOCX
Correlation Example
9 slides1.3K views
DOC
Sem Ski Amos
8 slides500 views
PPT
Sem+Essentials
55 slides1.7K views
DOC
Path Spss Amos (1)
17 slides5.7K views
DOC
How To Succeed In Graduate School
26 slides620 views
PPT
Actionscript 3 - Session 4 Core Concept
24 slides1K views
PPT
Actionscript 3 - Session 3 Action Script And Flash
16 slides2.2K views
PPT
Actionscript 3 - Session 1 Introduction To As 3
11 slides2.9K views
PPT
Actionscript 3 - Session 5 The Display Api And The Display List
5 slides945 views
PPT
Actionscript 3 - Session 6 Interactivity
11 slides1.3K views
Class Diagram | OOP and Design Patterns by Oum Saokosal
15 slides1.1K views
Java OOP Programming language (Part 1) - Introduction to Java
14 slides669 views
Aggregate rank bringing order to web sites
8 slides649 views
How to succeed in graduate school
26 slides1.1K views
Google
20 slides812 views
E miner
132 slides1.7K views
Data preparation for mining world wide web browsing patterns (1999)
27 slides4.1K views
Consumer acceptance of online banking an extension of the technology accepta...
12 slides5.5K views
When Do People Help
2 slides417 views
Mc Nemar
5 slides5.9K views
Correlation Example
9 slides1.3K views
Sem Ski Amos
8 slides500 views
Sem+Essentials
55 slides1.7K views
Path Spss Amos (1)
17 slides5.7K views
How To Succeed In Graduate School
26 slides620 views
Actionscript 3 - Session 4 Core Concept
24 slides1K views
Actionscript 3 - Session 3 Action Script And Flash
16 slides2.2K views
Actionscript 3 - Session 1 Introduction To As 3
11 slides2.9K views
Actionscript 3 - Session 5 The Display Api And The Display List
5 slides945 views
Actionscript 3 - Session 6 Interactivity
11 slides1.3K views

Recently uploaded (20)

PDF
Approach and Philosophy of On baking technology
30 slides293 views
PDF
NewMind AI Weekly Chronicles - August'25 Week I
49 slides118 views
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
11 slides90 views
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
5 slides77 views
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
10 slides85 views
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Big Data Technologies - Introduction.pptx
21 slides128 views
PDF
cuic standard and advanced reporting.pdf
67 slides71 views
PPT
Teaching material agriculture food technology
39 slides84 views
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
9 slides61 views
PDF
Network Security Unit 5.pdf for BCA BBA.
15 slides65 views
PDF
Review of recent advances in non-invasive hemoglobin estimation
18 slides113 views
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
65 slides80 views
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
10 slides74 views
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
1 slide149 views
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
15 slides79 views
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
2 slides71 views
PDF
Electronic commerce courselecture one. Pdf
31 slides70 views
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
17 slides91 views
PPTX
Understanding_Digital_Forensics_Presentation.pptx
40 slides97 views
Approach and Philosophy of On baking technology
30 slides293 views
NewMind AI Weekly Chronicles - August'25 Week I
49 slides118 views
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
11 slides90 views
CIFDAQ's Market Insight: SEC Turns Pro Crypto
5 slides77 views
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
10 slides85 views
Chapter 3 Spatial Domain Image Processing.pdf
Big Data Technologies - Introduction.pptx
21 slides128 views
cuic standard and advanced reporting.pdf
67 slides71 views
Teaching material agriculture food technology
39 slides84 views
Mobile App Security Testing_ A Comprehensive Guide.pdf
9 slides61 views
Network Security Unit 5.pdf for BCA BBA.
15 slides65 views
Review of recent advances in non-invasive hemoglobin estimation
18 slides113 views
Reach Out and Touch Someone: Haptics and Empathic Computing
65 slides80 views
GamePlan Trading System Review: Professional Trader's Honest Take
10 slides74 views
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
1 slide149 views
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
15 slides79 views
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
2 slides71 views
Electronic commerce courselecture one. Pdf
31 slides70 views
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
17 slides91 views
Understanding_Digital_Forensics_Presentation.pptx
40 slides97 views

Java OOP Programming language (Part 4) - Collection

  • 1. Java Programming - Collection Oum Saokosal Master’s Degree in information systems,Jeonju University,South Korea 012 252 752 / 070 252 752 oumsaokosal@gmail.com
  • 2. Contact Me • Tel: 012 252 752 / 070 252 752 • Email: oumsaokosal@gmail.com • FB Page: https://facebook.com/kosalgeek • PPT: http://www.slideshare.net/oumsaokosal • YouTube: https://www.youtube.com/user/oumsaokosal • Twitter: https://twitter.com/okosal • Web: http://kosalgeek.com
  • 3. 3 Agenda •Building arrays •Vectors and Hashtables •Data structures introduced in Java 2 •Using wrappers to convert primitive data types to objects •Handling exceptions
  • 4. 4 Arrays • Accessingarrays • Accessarraysby supplying the indexin square bracketsafter the variable name,variableName[index] • The first indexis0, not 1 • Example • Here, the argument to main is an array of Strings called args public class Test { public static void main(String[] args) { System.out.println("First argument: " + args[0]); } } > javac Test.java > java Test Hello There First argument is Hello
  • 5. 5 The Array length Field • Arrays have a built-in field called length that storesthe size of the array • The length is one bigger than the biggest index, due to the fact that the index starts at 0 • Example public class Test2 { public static void main(String[] args) { System.out.println("Number of args is " + args.length); } } > javac Test2.java > java Test2 Number of args is 0 > java Test2 Hello There Number of args is 2
  • 6. 6 Building Arrays • Arrays can be built in a one-step or two- step process 1. The one-step process is of the following form: type[] var = { val1, val2, ... , valN }; • For example: int[] values = { 10, 100, 1000 }; Point[] points = { new Point(0, 0), new Point(1, 2), ... };
  • 7. 7 Building Arrays, cont. 2. With the two-step process, first allocate an array of references: type[] var = new type[size]; • For example: int[] values = new int[7]; Point[] points = new Point[length]; • Second, populate the array points[0] = new Point(...); points[1] = new Point(...); ...
  • 8. 8 Multidimensional Arrays •Multidimensional arrays are implemented as an arrayof arrays int[][] twoD = new int[64][32]; String[][] cats = { { "Caesar", "blue-point" }, { "Heather", "seal-point" }, { "Ted" , "red-point" } };
  • 9. 9 Data Structures • Java 1.0 introduced two synchronized data structures in the java.util package • Vector • A stretchable(resizable) array of Objects • Time to accessan element is constant regardlessof position • Time to insert element is proportionalto the size of the vector • Hashtable • Stores key-value pairs as Objects • Neither thekeysor values can be null • Time to access/insert is proportionaltothe size of the hashtable
  • 10. 10 UsefulVector Methods • addElement / insertElementAt / setElementAt • Add elementsto the vector • removeElement / removeElementAt • Removesan element from the vector • firstElement / lastElement • Returnsa reference to the first and last element,respectively (without removing) • elementAt • Returnsthe element at the specified index • indexOf • Returnsthe indexof an element that equals the object specified • contains • Determinesif the vector containsan object
  • 11. 11 UsefulVector Methods (cont) • elements • Returns an Enumerationof objects in the vector Enumeration elements = vector.elements(); while(elements.hasMoreElements()) { System.out.println(elements.nextElement()); } • size • The number of elements in the vector • capacity • The number of elements the vector can hold before becoming resized
  • 12. 12 Useful Hashtable Methods • put / get • Stores or retrievesa value in the hashtable • remove / clear • Removesa particular entry or all entriesfrom the hashtable • containsKey / contains • Determinesif the hashtable containsa particular key or element • keys / elements • Returnsan enumeration ofall keysor elements,respectively • size • Returnsthe number of elementsin the hashtable • rehash • Increasesthe capacity ofthe hashtable and reorganizesit
  • 13. 13 Collections Framework •Additional data structures Collection Set SortedSet List ArrayList LinkedList Vector* HashSet TreeSet Map SortedMap HashMap Hashtable* TreeMap Interface Concrete class *Synchronized Access
  • 14. 14 Collection Interfaces • Collection • Abstract classfor holding groupsofobjects • Set • Group of objectscontainingno duplicates • SortedSet • Set of objects(no duplicates)stored in ascending order • Order is determined by a Comparator • List • Physically (versus logically)ordered sequence ofobjects • Map • Stores objects(unordered)identified by unique keys • SortedMap • Objectsstored in ascending order based on their key value • Neither duplicate or null keysare permitted
  • 15. 15 Collections Class • Use to create synchronized data structures List list = Collection.synchronizedList(new ArrayList()); Map map = Collections.synchronizedMap(new HashMap()); • Provides useful (static) utility methods • sort • Sorts (ascending) theelementsin thelist • max, min • Returns the maximum or minimum element in the collection • reverse • Reverses the order of theelements in the list • shuffle • Randomly permutes theorder of the elements
  • 16. 16 WrapperClasses •Each primitive data type has a corresponding object (wrapperclass) Primitive Corresponding Data Type Object Class byte Byte short Short int Integer long Long float Float double Double char Character boolean Boolean
  • 17. 17 Wrapper Uses • Defines useful constants for each data type • For example, Integer.MAX_VALUE Float.NEGATIVE_INFINITY • Convert between data types • Use parseXxx method to convert a String to the correspondingprimitivedata type try { String value = "3.14e6"; double d = Double.parseDouble(value); } catch (NumberFormatException nfe) { System.out.println("Can't convert: " + value); }
  • 18. 18 Exception Hierarchy •Simplified Diagram of Exception Hierarchy Throwable Error IOException RuntimeException Exception …
  • 19. 19 ThrowableTypes • Error • A non-recoverableproblem that should not be caught (OutOfMemoryError, StackOverflowError, …) • Exception • An abnormalcondition that should be caught and handled by the programmer • RuntimeException • Special case; does not have to be caught • Usually the result of a poorly written program (integer division by zero, array out-of-bounds,etc.) • A RuntimeException is considereda bug
  • 20. 20 Multiple CatchClauses • A single try can have more that one catch clause • If multiple catch clauses are used, order them from the most specific to the most general • If no appropriatecatch is found,the exception is handedto any outer try blocks • If no catch clause is found within the method, then the exception is thrown by the method try { ... } catch (ExceptionType1 var1) { // Do something } catch (ExceptionType2 var2) { // Do something else }
  • 21. 21 Try-Catch, Example ... BufferedReader in = null; String lineIn; try { in = new BufferedReader(new FileReader("book.txt")); while((lineIn = in.readLine()) != null) { System.out.println(lineIn); } in.close(); } catch (FileNotFoundException fnfe ) { System.out.println("File not found."); } catch (EOFException eofe) { System.out.println("Unexpected End of File."); } catch (IOException ioe) { System.out.println("IOError reading input: " + ioe); ioe.printStackTrace(); // Show stack dump }
  • 22. 22 The finally Clause •After the final catch clause, an optional finally clause may be defined •The finally clause is always executed, even if the try or catch blocks are exited through a break, continue, or return try { ... } catch (SomeException someVar) { // Do something } finally { // Always executed }
  • 23. 23 Thrown Exceptions • If a potential exception is not handled in the method, then the method must declare that the exception can be thrown public SomeType someMethod(...) throws SomeException { // Unhandled potential exception ... } • Note: Multiple exception types (comma separated) can be declared in the throws clause • Explicitly generating an exception throw new IOException("Blocked by firewall."); throw new MalformedURLException("Invalid protocol");