0% found this document useful (0 votes)
6 views

Part 3 - Java programming Advanced 1

The document provides an advanced overview of Java programming, focusing on exception handling, input-output operations, and the collections framework. It covers best practices for managing exceptions, including checked and unchecked exceptions, the use of try-catch blocks, and the try-with-resources statement for resource management. Additionally, it discusses various data structures in Java, such as lists, queues, sets, and maps, along with their implementations and interfaces.

Uploaded by

montadhr.social
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Part 3 - Java programming Advanced 1

The document provides an advanced overview of Java programming, focusing on exception handling, input-output operations, and the collections framework. It covers best practices for managing exceptions, including checked and unchecked exceptions, the use of try-catch blocks, and the try-with-resources statement for resource management. Additionally, it discusses various data structures in Java, such as lists, queues, sets, and maps, along with their implementations and interfaces.

Uploaded by

montadhr.social
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Java programming

Advanced
1. EXCEPTIONS WITH BEST PRACTICES ......................................................................................................... 4
1.1. BASICS ............................................................................................................................................... 4
1.1.1. Generate exception .................................................................................................................. 4
1.1.2. Handle one exception............................................................................................................... 5
1.1.3. Multiple exceptions .................................................................................................................. 6
1.1.4. Exception can be referenced polymorphically ........................................................................... 6
1.2. CHECKED UNCHECKED EXCEPTIONS ........................................................................................................... 7
1.2.1. Checked exceptions .................................................................................................................. 8
1.2.2. Unchecked exceptions .............................................................................................................. 8
1.3. FINALLY BLOCK ..................................................................................................................................... 9
1.4. TRY-WITH-RESOURCES STATEMENT ......................................................................................................... 10
1.5. SUPPRESSED EXCEPTIONS ...................................................................................................................... 13
1.6. CREATING NEW EXCEPTIONS (BEST PRACTICES) .......................................................................................... 15
1.7. ASSERTIONS ...................................................................................................................................... 19
2. INPUT-OUTPUT ...................................................................................................................................... 23

2.1. CHARACTER ENCODING (PREREQUISITE) ................................................................................................... 24


2.2. STREAM IO ....................................................................................................................................... 25
2.2.1. Byte Streams.......................................................................................................................... 27
2.2.1.1. Input Stream .................................................................................................................................... 27
2.2.1.2. Output Stream ................................................................................................................................. 28
2.2.1.3. Reading Byte-Oriented Files Efficiently: Decorator Pattern ................................................................ 29
2.2.1.3.1. Decorator pattern ...................................................................................................................... 29
2.2.1.3.2. File Input Stream ........................................................................................................................ 31
2.2.1.3.3. File Output Stream ..................................................................................................................... 31
2.2.1.3.4. Chained streams......................................................................................................................... 32
2.2.1.3.5. Buffered Stream ......................................................................................................................... 32
2.2.2. Character Streams ................................................................................................................. 35
2.2.2.1. Reader class ..................................................................................................................................... 35
2.2.2.2. Writer class ...................................................................................................................................... 36
2.2.2.3. Reading Writing Text Efficiently ........................................................................................................ 37
2.2.3. Download webpage ............................................................................................................... 40
2.2.4. File Class ................................................................................................................................ 40
2.3. SERIALIZING JAVA OBJECTS .................................................................................................................... 42
3. COLLECTIONS FRAMEWORK (DATA STRUCTURES) ................................................................................. 46
3.1. COLLECTION INTERFACE ........................................................................................................................ 47
3.2. LIST INTERFACE AND THEIRS IMPLEMENTATIONS .......................................................................................... 48
3.2.1. List Interface .......................................................................................................................... 48
3.2.2. Array List ............................................................................................................................... 49
3.2.3. Linked List .............................................................................................................................. 51
3.3. ITERATOR AND LISTITERATOR ................................................................................................................. 53
3.3.1. Iterable interface ................................................................................................................... 53
3.3.2. Iterator interface ................................................................................................................... 54
3.3.3. List Iterator ............................................................................................................................ 55
3.4. QUEUE INTERFACES ............................................................................................................................. 57
3.4.1. Queue Interface ..................................................................................................................... 57
3.4.2. Deque Interface ..................................................................................................................... 57
3.4.3. Array Deque........................................................................................................................... 59
3.5. HASH TABLE ...................................................................................................................................... 60
3.5.1. Hash code (method of Object class) ........................................................................................ 62
3.5.2. Equals method (method of Object class) ................................................................................. 62
3.6. SET INTERFACE AND THEIRS IMPLEMENTATIONS .......................................................................................... 63
3.6.1. Set interface .......................................................................................................................... 63
3.6.2. Hash Set (Item 52) ................................................................................................................. 64
3.6.3. LinkedHashSet ....................................................................................................................... 64
3.6.4. Sorted Set interface................................................................................................................ 65
3.6.4.1. Navigable Set ................................................................................................................................... 66
3.6.5. Tree Set (Comparable Comparator) ........................................................................................ 68
3.7. MAP INTERFACE AND THEIRS IMPLEMENTATIONS ........................................................................................ 70
3.7.1. Map Interface ........................................................................................................................ 70
3.7.2. Hash map implementation ..................................................................................................... 73
3.7.3. Linked Hash Map ................................................................................................................... 73
3.7.4. Sorted Map ............................................................................................................................ 76
3.7.5. Navigable Map ...................................................................................................................... 77
3.7.5.1. Tree Map implementation ................................................................................................................ 77
3.8. ARRAYS CLASS ................................................................................................................................... 77
3.9. COLLECTIONS CLASS ............................................................................................................................ 81
1. Exceptions with Best Practices
 Motivation :
 As professional programmers we all want our code to be as error free as possible.
But all our first to write error free programs at run time, we must count some
errors and normally such errors are exceptions rather than none that is happen
only in:
o Exceptional situations
 Partner server that provide web service is down: connect to another
server and this server is inaccessible
 Database is down

 These things not in our control

 Good programmer thing about this situations and would write code to handle them

This leads to robust software otherwise your code will be very fragile

1.1. Basics
 An exception is simply an object (like any others java objects) of the class Throwable or
one of its subclasses.

 Throwable is super class of all exceptionally literal classes


 Exceptions indicate an exceptional situation like partner server going down. In this case a
method or the constructor generate an exception

1.1.1. Generate exception


 We can generate an exception when we have an exceptional situation by keyword throw
followed by instance of one subclasses of Throwable like this example:

 When we generate exception in particular method and we don’t handing it in this method,
we should indicate this exception in method declaration for reason to all others methods
use this particular method know that this method generate new exception we it’s should
handled it.

 To indicate this exception in method declaration, you should use keyword throws
followed by one or more class’s exception like this example
 You can handle in method declaration many exceptions class separated by ‘,’ like this
example:

1.1.2. Handle one exception


 You can handle an exception by using try/catch block like this example

 When an exception is generate in try block, then the code in catch block will executed
automatically
 Catch block take like parameter instance of exception that it will handler
 If you want to write an recovery code when an exception is generated, you need to write
it in catch block
 When exception is generated in try block then all rest of code in this block will be
skipped and will execute handler code in catch block
 You can handle generated exception in any part of tree called methods of method
when you have generation exception
 If an exception is generated, all rest of code will be skipped until find handler
block (try/catch), the exception will be passed to the JVM and JVM will first see if there is
an exception handling code within this method and it’s not there. Then it’s go to the call stack
or all tree of methods and its try to see if there is an exception handler in call stack. If
o Exist exception handler in method or call stack: then it execute catch
block
o Not exist: it print exception message and tree of exception itself in
console and then skip all rest of code

1.1.3. Multiple exceptions


 You can add many catch blocks to try block this for reason to handle many exceptions
like this example:

 When you have relation of subclass and super class in many catch blocks you should
placed that from subclass to super class (subclass exception handler should be first
than super class) otherwise you get compiler error.

1.1.4. Exception can be referenced polymorphically


 When you have 2 exception classes when one is super class of other exception class, then
you can handle all exception generated for subclass by using super class. In this example
we have example of this part:
 You shouldn’t use this method when you have 2 different recovery handlers for
subclass and super class.

1.2. Checked Unchecked Exceptions


 In java, programs can generate either checked or unchecked exceptions
1.2.1. Checked exceptions
 They are cost by exceptions situation that are simply not under our control for example
partner would be down or database unavailable.
 With checked exception, you should handle it in your code because the compiler will
force programmer to handle checked exception
 When you generate checked exception, the company will granite 2 thinks:
 Specify in throws clause: Announce that you are throwing the exception by
specifying it in the method declaration using throws keyword
 Exception handling via try/catch: invoking code must acknowledge the
exception by wrapping the calling code in try/catch block or just in done really the
exception for the next higher level method to handle it

1.2.2. Unchecked exceptions


 There are generated by either programming flows or do some internal system errors like
out of memory error
 Compiler will not force programmer to handle unchecked exception
 There exceptions are not checked by compiler (if generate these exceptions and not
handled it, you don’t have compiler error). There is you can throw them anywhere and
the compiler does not both checking whether or not they are specified in method
declaration or whether or not they are handled by invoking code. All there are optional (if
you want handle it or not)
 There are 2 types of unchecked exceptions:
 Runtime exceptions: programming flows (minimized at development and testing)
o Due to programming errors You want them to happen mostly development
and testing time
o Its optional to catch it but it’s not recommended to catch these type of
exceptions
o Example: parsing a response from web service and you counter problem
parsing some piece of data(format of date field might have changed in this
because when you try to parse the date you have unchecked exception
 ideally, with good development and testing effort, you would want as minimal
runtime exceptions as possible
 Generally you shouldn’t catch runtime exceptions as there are due to
programming errors. Usually recovery from such exceptions is impossible and
continued execution would do more harm than good. But sometimes you want to
catch them too
 It’s not good to catch unchecked exception (runtime exceptions) because it’s bugs
in programming code
 Errors: internal system errors
o It there’s a JVM related under normal conditions
o They occur rarely. When they do occur the JAVA program terminate
o They are to do dome abnormal conditions a reasonable application would not
be expected to catch it
 You would almost catch an error
1.3. Finally block
 With this block, we seeing how exceptions can affect the control for itself that is
awesome many steps for treating exception by JVM:
 this exception is generated
 rest of try block is skipped
 JVM start looking for matching exception handler normally suck control is fine
 But sometimes the code might be using operating system resources like closing
database connection or output stream) is such cases you would have same extra care.
 For instance here is send method file output stream would have operating system
resources to connect to the destination file and these system resources once used have to
be closed appropriately to avoid any resource leaks. The problem than we have is in this
picture. If exception is:
o Not generated then we should close output stream in try block.
o Generated and we have exception handler: we should close output stream in each
catch block.
o Generated and we haven’t exception handler or unchecked exception is generated:
then we should close output stream after try/catch block.

 So we need one invocation statement and it need to executed for sure we need
guaranty.
 For that we need use finally block. It’s an optional block and when present it always
executed. It not executed only when there are severe JVM error or system exit
(terminate JVM itself)
 Finally block must followed (after) catch blocks. We cannot put finally block between try
and catch blocks or between 2 catch blocks. If catch block not exist then it can be
followed try block
 Try block must have at least one catch or finally blocks
 We cannot have more than finally blocks associated with try block
 We look now control flow when finally block is exist:

1.4. Try-with-resources Statement


 Try with resources is introduced in java 7
 It has something to do with the try block and also with resources
 Resources would be classes which present something like operating system
resources like file handles which are using to performing IO related operations
like reading from a file
 Main thing the statement is to automatically close such resources.
 To understand the benefit of try with resources first let’s look an example
 It’s a standard template which was used before java 7 for reading data from a file
 In try block we are first creating file input stream instance which access resource
to read data from it
 There are catch block to handle file not found exception which is thrown with
constructor of file input stream class
 Finally block with file input stream instance is closed. We have try catch block
because close resource can be throw IO exception.

 In this example we have finally block is very ugly with the try/catch block and the
additional null check and also close method invocation
 To avoid this, we have try-with-resources statement introduced in java 7. Here in the
next picture we have the same code but with try with resources. Its looks much cleaner
without finally block and we have only try/catch block

 Here resources are created within parenthesis that follows the try keyword.
Declaration is done within the parenthesis and it not work if declaration is done
outside of parenthesis and initialization is done within parenthesis
 With try with resources, the entire cleanup operation is taken care of implicitly the
close method is invoked implicitly after the try block is executed (Automatic
resource management ARM)
 In reality the compiler inserts in the end finally block into the byte code. If an
exception is generated, the close method is still invoked just in the case of using
finally block explicitly
 The resources created (variable ‘in’) in the parenthesis is implicitly final. So it
cannot be reassigned within the try block
 All exceptions generated in implicitly finally block in try-with-resources are
suppressed (not importants)
 Try-with resources, multiple resources:

 The resources creation expressions must be separated by semi-colons like for


loop
 All resources created in try-with-resources are closed implicitly in finally block
and its closed as the reverse order of creations (last created is first closed)

 General syntax:

 Any resource are created in parenthesis must be of type of AutoCloseable which


is interface of java.lang package. Means the class of the resource must be
implement AutoCloseable interface or one of its subclasses
 AutoCloseable has one method which is the close method
 Catch or finally not requirement: Try block need not have catch block if the close
method which you implement does not throw an exception and the code within try
block should not throw an exception
 AutoCloseable hierarchy:
1.5. Suppressed Exceptions
 Its take care of automatically by try with resources syntax So in try-with-exceptions
 When generate exception in try block, So this is the main exception was been
generated by this method
 Exceptions generated by all resources were embedded within encapsulated within
this exception as suppressed exceptions
 In normal try/catch block, the first exception generated will be returned and the
others exceptions will be ignored and we need to fixed it manually
 Example of:
 Suppressed exception in try-with-resources block:
o In normal exception, the exception will be generated is “Trivial exception”
and will be ignored all others exceptions also “Important exception” for
many reasons exist in next part
o But in this case all trivial exceptions are suppressed (not important) and
the main exception that will be generated is “Important exception”

 Ignored exception (no suppressed exceptions) in try/catch:


o the exception will be generated is “Trivial exception” and will be ignored
all others exceptions also “Important exception” for many reasons exist in
next part
 First exception generated is “important exception”.
 After, JVM will search exception handler with catch.
 After, it execute finally block, in this case finally block have same
type of exception “Trivial exception”
 So the second exception “Trivial exception” will be handled
o If the exception generated in finally block is haven’t same type of
exception generated in try block then we have compiler error

 Generate suppressed exception in try/catch resources:


o To solve this problem you need to
 First, catch the exception generated in try block “important
exception” and assign exception hatched in local variable for
method
 Second, in finally block you need to you need to handler the
exception generated in this block and use method of exceptions
class called addSuppressed to the variable contain exception
generated in try block and pass the new exception like parameter
1.6. Creating New Exceptions (Best Practices)
 You need to extend one of exceptions classes to create new exception,
 To create :
 Checked exception: you need to extends on of checked exception classes (other
exception class then runtime exception and error and their subclasses)
 Its nor recommended to extends Throwable class when you need to create new
exception
 Runtime error (unchecked): you need to extends runtime Error or one of theirs
subclasses

 You should not extends Error, you should not sub classed it and that’s because there is a
strong convention that errors should be generated only by the JVM because its JVM
related and there are abnormal conditions. You can do its but you shouldn’t do it
 Item 58: Use checked exceptions for recoverable conditions and runtime
exceptions for programming errors.
 Its recommended to use :
o Checked exceptions: when you have recoverable conditions. That’s means
when you have exception situation like partner would be down or database
unavailable.
o Runtime exception: when you have programming error. That’s mean for
example in division operation you cannot have Zero in divisor.
 Should I use Checked or Unchecked? An important role in deciding to go with
a checked exception would be:
o That it happened due to some exceptional situation and not programming
error.
o Caller can be expected to reasonably recover from it
 Item 65: don’t ignore exceptions.
 It neither’s nor recommended in java programming to ignore exception.
 A very common mistake is to ignore exceptions by using empty catch blocks. If
the API designer is throwing a checked exception, then catching it with an empty
catch block implies that you are ignoring the exceptional situation, which the item
relates to a fire alarm.
 Similarly, if an empty catch block is catching an unchecked exception, then it is
equally dangerous as the program might continue to work silently, but might
result in some other very serious errors.
 You can ignore exception by handle exception by catch block but you don’t do
any treatment in catch block (empty catch block) like this example:

 This way is not recommended in best practice programming. You should do


anything in this block like print error in console or any treatment you need (like
e.printStackTrace).
 If you do that at the very least, it is recommended to include a comment
indicating why it is okay to ignore the exception.
 Item 63: include failure capture information in detail message.
 Sometimes stack trace alone may not be helpful to the debugger
 Debugger need some additional information’s in order to fix the problem and he
want to reproduce the problem and it might be very difficult to reproduce the error
 It basically say it basically just to include as much information as possible from
the context when exception has been generated like
o parameters information,
o any instance variable information
 to encapsulate that in the exception itself
 you can pass these information’s to exceptions by personalize the constructor
of exception class like this example:
 It’s better to have more additional information’s along with the exception (will be
very useful
 Item 61: Throw exceptions appropriate to the abstraction
 In multi layer system (when you have multi layers),
o The higher layer level and the lower layer level and
o We have higher level method invoke lower level methods and
o If higher level layer catch exception from an lower layer level
 then instead to propagate that exception, it should throw new exception higher level
layer that is more meaningful in term of higher level abstraction (higher level layer is
not polluted with lower layer level (exception translation)
 In some situations, when debugger need access to lower level layer to debugging.
Then you can use type of exception translation called Chaney similar to details
message, the higher level exception can encapsulate the lower level exception.

 You can do this by using constructor of exception when you pass message and
throwable class
 Item 57: Use exceptions only for exceptional conditions
 Don’t use them for regular control flow
 For example use next item in try catch and in last item when you use next item method
it throw an exception. This is regular control flow like this picture

 Don’t rely exception blocks in control flow


 Item 59: Avoid unnecessary use of checked exceptions
 Checked exception are great it make your program reliable in the event of any
exceptional conditions
 But if use carelessly then they would make the API far less presently use as the false
the API class and to handle those exceptions (Unpleasant API) so this is an extra
burden on the client
 So use them only if:
o Unpreventable exceptional conditions
o The API client can actually recover from it (client should recover it)

 If one or both of these conditions do not hold, then an exception would be more
appropriate.

 Item 60: Favor the use of standard exceptions


 That’s because the exception that come with java API should be good enough most of
the time
 So you don’t have to introduce any new exception classes
 There are same benefits of reusing existing exceptions:
o Using standard exception would make it easy to understand your API
o Consequently it would also make the program so your API client easy to
follow and read
 Here few commonly used exceptions: IllegalArgumentException,
NullPointerException, IndexOutOfBoundsException
 Item 62: Document all exceptions thrown by each method
 It’s very important to describe all the exceptions that a method can throw
 It help using the method properly
 Generally this addition is also often by later. Sometimes even public APIs
 Checked exceptions:
o Declare and document each exception precisely indicating the conditions under
which each one is thrown
o Don’t Throws Exception or Throwable. Doing this will effectively obscure
(masquera) any specific exception that may be throw by the method. So use
specific exception rather than generic ones
 Unchecked exceptions:
o Its optional to declare them or document them as carefully as checked
exceptions
o Generally majority of unchecked exceptions are thrown in prevent of
preconditions violations.
o Recall preconditions violations is simply a failure by API client to stick to the
API contract
o Its recommendation to document unchecked exception but do not declare them
o It’s important to document unchecked exceptions thrown by interface methods.
These documentation would be part of interfaces contract and therefore unable
common behavior among its different implementation
 This is will help any programmer looking to your method to clearly distinct which
checked exceptions from unchecked ones

 Take time to carefully document all exceptions that your method throws by using
annotation @throws used for document exceptions
 Item 38: check parameters for validity
 It’s a preconditions checks which we already discussed
 Should think about parameters restrictions (‫ )قيود‬when writing new method or
constructors
 If there are any restrictions, you need to check them at beginning of the method and
throw any unchecked exceptions and also document them
 For non public methods, its recommended to do parameter checks using another
feature of java called Assertions which we will se next

1.7. Assertions
 They are mainly about detecting errors during development and testing time
 There are 2 factors that contribute to software liability
 Robustness: is software’s ability to withstand any errors that may happen in
exceptional situations. That is software should be continue to execute in such
situations
 Can do that using exceptions and exception handling
 Correctness: deals with software correctly
 Assertions can help with correctness
 Normally when we develop software we write our code based on what we gather from
our product managers or any requirement documentations.
 In the process, we make certain assumptions (‫ )االفتراضات‬and most of the time
these assumptions would be right. But sometimes they may wrong to and it would
be ideal to detect them at development time itself
 So assumptions are kind of Boolean expressions and we need to be able to test it and
assertions would helpful in testing our assumptions. That is correctness of our
programs

 Syntax: an assert statement has 2 forms:


 assert Boolean-expresion: Using assert keyword followed by Boolean
expression: this statement test a Boolean expression
o If Boolean expression evaluates to true then everything is good and control
goes to the next statement.
o Otherwise they implies that the program is not working correctly there is
something wrong in our assumption in this case an error called
AssersionError (subclass of Error class) thrown and the program
terminated immediately as there is no point continuing when the program
is working incorrectly

 Assert Boolean-expression: message. using assert keyword followed by Boolean


expression followed by colon followed by error message
o in this case if Boolean expression evaluate to false then an assertion error
is thrown but is initialize with the error message

 An assert statement simply checks a boolean condition, and does nothing if it is true but
immediately terminates the program if it is false
 benefits:
 assertions are very effective in quickly detecting by bugs during development
time
 it implies an assumption that you think is right so if it fails for particular instance
of data then it means that your assumption is wrong and you have to fix it
 It serves as documentation. In some situations assertions can be better than
comments for example let’s assume there is a non obvious competition and there
is also comment explaining that but if some of assumption change and
consequently the competition logical changes then comments will also have to
change otherwise comment can get out of date. But assertions on the other hand
check it runtime and so would most likely fails and will force the developer to
update them
 In that sense assertions are like active comments
 (Item 38) Assertions can be used in anywhere in the program but one good place to use
that is for validating parameters if parameter have any restrictions or preconditions as this
particular item recommended (item 38)
 Public methods: the item suggests throwing an unchecked exception if there is
violation of preconditions. This would be programming error in the API client
 You shouldn’t use assertions in public methods because:
 Assertions are disabled by default
 Assertions throw universal assertion error which may not be helpful for API clients in
fixing problem
 Non public methods: the item suggests using assertions
 Assertions are not in working directly by API client it is internal code that is invoking
them
 The owner of code would be expected to test them extensively during development with
help of assertions. This way in production non public methods should always be
invoked by correct parameter values
 Can have Junit and assertions in same code?
 Assertions are complement unit testing
 Unit testing is all about automated repeatable testing of program correctness. That
is non of program changes should break out tests
 Should use assertion in:
o Update some logic or your project and relevant assertions then how would
you test new logic
 Junit is about entire methods itself and not about method parameters or a single
statement within a method. Its generally about block of code
 But with assertions most of the time its less granular like single statement or
validating one parameters
 Enabling or disabling assertions:
 They are disabling by default. To ensure that they are not performance liability on
production systems
 To enable them, the command line –ea (or –enableassertions) can be passed to
java interpreter.
 It can enable or disable at specific class and package level too
o To enable: -ea
o To disable: -da

 To enable or disable assertions using eclipse you can go to run as > run
configuration > Arguments and in JVM argument you write the command
2. Input-Output
 In any software, it’s very common to read data from some source and also to write some
data to some destination
 Source or destination can be a file which can be on local machine or even on some
remote FTP server. In this case, you can read something from file or write some things
into a file
 Example: read data from CSV file or generating CSV file
 I/O layer is simply a software component that specialized in doing a reading and
writing
 Similarly, when interacting with web service like REST API, you would request some
data and process the response and when requesting the data you may sometimes to
send some data to the API that is the write data into the network which will be passed
into the API server
 Sometimes, we have to download web pages (for example in our app we would
download all the web links in the system)

 There are 2 packages using for input and output:


 Java.io - stream IO: We will etude this package because its commonly used
 Java.nio - new IO: (since java 4)
 In this chapter we will see Stream IO in 2 different types (2 sub packages) :
 Byte streams: used for handling binary data such as images. We will see also:
 In this chapter design pattern called decorator pattern
 How we can save regular java object to disk and how we can read them back from
the disk
 Character streams: used for handling characters data like text files. We will see also:
 How we can collect input from the user using the console (command prompt)
2.1. Character Encoding (Prerequisite)
 Most people classifies files into 2 categories:
 Binary file: would include content like images audio and video
 Text file: is about files with characters
 However, fundamentally all files are binary that a sequence of bytes where each byte is
group of 8 bits and bit is 0 or 1
 Text files is also binary files it’s just that is stored in a certain way in binary
 All files binary or text look alike to hardware
 Software would make a distinction:
 Text file: is handling by text processing software like notepad, eclipse
 Bytes like images are only handle by image processing software like windows
photo viewer or windows paint application
 Hexadecimal:
 Computers use hexadecimal numbers to represent bytes like this example

 The same bit pattern would represent something else in an image file
 Single byte can be any of 256 patterns (28 ). It represent as many as 256characters
using different variations of a byte
 But to represent more characters we need to use more than one byte
 Processing text is very complex due to the numbers of ways in which characters in those
languages can be represented  So numbers of encoding schemas
 All programs like browser is not understand all characters of words. So any character not
understands it will replace with ? (usually for international characters)
 Encoding schemas:
 Every file uses some encoding schema to represent content.
 It’s basically an algorithm which maps characters to hexadecimal numbers and
whose binary representations are used for storage
 Example encoding schemas: ASCII, UCS-2, UTF-16, UTF-32
 Each encoding schemas is implementation of some characters for example UTF-
16 and UTF-32 are all implementation of Unicode characters
 Character set:
 ASCII: 7-bit for unaccented English characters

 ISO/IEC 8859: standard 8-bit ASCII extensions. It cover 50different variation for
50 different regions in the word
 DBCS (Double Byte Character Sets): Asian characters
 Resulted in decoding issues: for instance a hexadecimal code of a particular character in
one country would correspond to a completely different character in some other country

 For these problems Unicode is come to cover all languages in the world
 Unicode:
 Maintained by Unicode consortium
 It is backward compatible with 7-bit US ACSII
 Initial assumption is that
o 16 bits which represent 65536 chars would suffice to cover all language
o These character together as group are referred to as Basic multilingual
Plane (BMP)
o UCS-2: its used exactly 16 bit to represent any character
 To get coding of string with Java you can use method get Bytes method and
passed to it name of encoding you need like these examples

2.2. Stream IO
 In stream IO reading and writing is handled by something called streams

 Stream
 It’s basically a connection between java program and a data source or sink
(destination)
 it’s basically represented by a class
 it’s also specific to the type of source or sink
o if source or sink is file: the you use specific type of stream
o when dealing with network different type of stream is used
 there are 2 types of stream:
o input stream: read some data from source
o output stream: write some data to a destination
 when working with streams, there are three operations that are involved
o open stream
o read/write data
o Close stream: would free system resources (socket or file handled) that the
stream would be used. Can close it inside finally block.
 The operating systems have limits on the number of sockets of file handles that can
open (you risk to can’t open any new stream). So you should close stream after used it
 Standard template for open and closing streams:

 Stream classification: streams are 2 types (because java differentiate between processing
character data and anything else
 Byte streams: used for non characters data like images. It have also 2 types
o InputStream: subclass for all classes used for reading non characters data
from anything
o OutputStream: based class for all non characters output stream
 Character streams: used for characters data like text. It have also 2 types
o Reader: based class for all characters input streams
o Writer: based class for all characters output stream
2.2.1. Byte Streams
 Byte streams are used when we want to build with raw bytes. That is e want to read row
bytes serially or write raw bytes serially
 Character streams are also build on top of byte streams

2.2.1.1. Input Stream


 It’s a base abstract class for on byte oriented input streams
 Used to read data in groups of 8 bit bytes
 Input stream hierarchy

 Read operation:
 Method for reading exactly one byte at a time:

o all subclasses should be implemented this method


o it reads exactly one byte
o return byte as integer value which will be between 0 and 255

o return -1 if end of stream is detected


 For example for character ‘a’, this method will return correspond decimally value 97
 Method used to read groups of bytes:

o Its concrete method, inherited by all subclasses


o It read more than one byte. Group of bytes
o Has 3 parameters :
 Byte array:
 Offset
 Length
 Method read length number of bytes from the input stream into the input array
starting from the index position offset
o If number of byte that can be read is less than length, then only those bytes are
read
o Return total numbers of bytes read
o Return -1 if end of stream is detected
o Internally is repeatedly invokes the abstract read method (of subclasses
invoked)
 There are another read method like this method and it take at input only byte array. It’s
simply same method but passed 0 like offset and length of input array like length. It
read the array completely starting from index position zero

 All read calls are blocked when no data are available (when data are not available,
then it will wait until the data become available) like reading data from network and
the sender not sending the data now.

2.2.1.2. Output Stream


 It’s a base abstract class for all byte oriented output streams like the input stream
 It’s used to write data in groups of 8 bit bytes
 Output stream hierarchy

 Write operations:
 Method for writing one byte at a time to the output stream
o Input parameter is an integer (32 bits) but this method needs to write only one
byte
o Its write the least significant byte that is the 8 lower order bits
 Method used to write groups of bytes

o
Its concrete method
It’s used to write groups of bytes
o
o
The content to write is store in input array (byte[])
o
Has 3 parameters :
 Byte array:
 Offset
 Length
o It will write length number of bytes from the input array starting at an index
position offset
o Internally is repeatedly invokes the abstract write method (of subclasses
invoked)
 There are another write method like this method and it take at input only byte array.
It’s simply same method but passed 0 like offset and length of input array like length.
It write the array completely starting from index position zero

2.2.1.3. Reading Byte-Oriented Files Efficiently: Decorator Pattern


 In this part, we how we can process byte oriented files that is files containing non textual
data like images
 Within IO, processing files is probably one of the most common activities
 We will see technique called buffering and design pattern called decorator pattern (it’s
very used in java IO package)

2.2.1.3.1. Decorator pattern


 Problem: You want to add behavior or state to individual objects at run-time. Inheritance
is not feasible because it is static and applies to an entire class.
 Decorator pattern allows a user to add new functionality to an existing object without
altering its structure. This type of design pattern comes under structural pattern as this
pattern acts as a wrapper to existing class.
 This pattern creates a decorator class which wraps the original class and provides
additional functionality keeping class methods signature intact.
 We are demonstrating the use of decorator pattern via following example in which we
will decorate a shape with some color without alter shape class.
 Very important design principle called the open closed principle serve as motivation for
decorator pattern. With this principle class should be open for extension but close for
modification. To add new functionality we are simply chain classes rather than modifying
them
 Example:

 We're going to create a Shape interface and concrete classes implementing the Shape
interface. We will then create an abstract decorator class ShapeDecorator
implementing the Shape interface and having Shape object as its instance variable.
 RedShapeDecorator is concrete class implementing ShapeDecorator.
 DecoratorPatternDemo, our demo class will use RedShapeDecorator to decorate
Shape objects.
2.2.1.3.2. File Input Stream
 It’s used for reading data from files
 Its subclass for Input stream
 We can create instance of file input stream using constructor with parameter string like
file name
 If file does not exist, the constructor does not create new file. It would simply throw a file
not found exception
 The constructor would generate File not found exception if:
 File to read does not exist
 File is directory
 Cannot be opened for any other reason

2.2.1.3.3. File Output Stream


 It’s used for writing data from files
 Its subclass for Output stream
 We can create instance of file output stream using constructor with parameter string like
file name

 This constructor would create new file if this file not exist but if file exist it would
override the file
 The constructor would generate File not found exception if:
 Cannot be created for writing
 File is directory
 Cannot be opened for any other reason

2.2.1.3.4. Chained streams

 Chained streams are that streams that are using the output of another stream as
their input in the pipe. (Example: BufferdInputStream)
 It’s like a dependent connection that uses an underlying Connection Stream or
another Chained Stream to receive output or feed input in order to complete end
to end connection.
 To provide buffering a buffer stream will be chain are connected to another
stream

2.2.1.3.5. Buffered Stream


 A basic read / write method where used for reading or writing single bytes is grossly
inefficient. It’s too expensive as each method invocation triggers in disk access. As
analogy it’s like shopping without a card.
 In programming terms that would correspond to something called buffering
 Using buffering you read or write block of bytes into a memory buffer and then you read
from memory buffer which is much faster than reading from the disk. Similarly, you
would also write a block of bytes into the memory buffer and then flush all of the data
that is once in a single IO operation.
 With memory buffer, we are not hitting the disk for each byte that we want to write
 Java Buffered Stream class is used to read / write information from stream. It internally
uses buffer mechanism to make the performance fast.
 The important points about Buffered Stream are:
 When the bytes from the stream are skipped or read, the internal buffer
automatically refilled from the contained input/output stream, many bytes at a
time.
 When a Buffered Stream is created, an internal buffer array is created.
 The memory buffering is nothing but simple byte array
 To do buffering, there are 2 specialize classes called
 BufferedInputStream : subclasses of FilterInputStream ( which is subclass of
InputStream )
 BufferedOutputStream : subclasses of FilterOutputStream (which is subclass of
OutputStream)
 Each class of these buffering classes have memory buffering (simple bytes array)
 The default buffer size is 8192 bytes but if we needed it we can change this value by
invoking one of constructors
 Buffer input and buffer output are not work independently. They work with other
streams like file output streams that is buffered streams only provide buffering as the
code functionality
 Buffered input stream is called as a decorator for file input stream that it is create the file
input stream object with addional buffer functionality.
 Constructor: We can create instance of buffer stream like this with chain it with another
byte stream

 Read Operations:
 Read method in buffer input stream

o It’s basically implementation of the abstract read method in the input


stream class
o If the buffer have some unread byte, the first unread is return
o Otherwise it will read some other bytes from the chain stream underline
stream (fill buffer with fresh data). In this case is file input stream
o This method is synchronized, so JVM allow one single thread to access to
this method in one time

 Read groups of bytes from input stream

o It will read length number of bytes from the buffer into the input array
starting in index position offset
o It return number of bytes read or -1 if end of stream is detected
o We will look now how method is implemented:
 If buffer have request amount of data, then data would be copied
from the buffer into the input byte array
 If buffer have not entire (‫ )كامل‬data, then
 The partial data it first copied into the input array.
 Next buffer is fill by fetching data from underline stream (
read method for chained stream is invoked )
 The buffer itself passed to the input itself.
 Finally the remaining data copied from the buffer into the
input array
 …

 Write operations:
 Write method of buffer output stream:

o It write input data to the buffer


o If buffer is full, then data in the buffer is first copied to the underlying
stream (chained stream: file output stream). Then buffer is filled the input
data
 Write input array content into the buffer

o It write length number bytes from the array starting at offset into buffer
o If buffer have not space, the buffer is first flushed (copied their content to
underlying stream: file output stream) and then array content are copied
into the buffer.
o To flush buffer the write method of the underlying chained stream is used
and simply passed buffer as argument

o But if input array size is greeted or equal to the buffer size then buffer is
fast flushed the input array are directly returned to the underlying stream
 Decorator.close():
 When close method for decorator is invoked then it would internally invoke the
close method of underlying decorator stream
 If the decorator is buffer output stream, then it invoke close method would fist
flush all buffer contents and then close then underlying stream is invoked. For
flushing internally flush method is used but you don’t have to invoke this method
explicitly as both right as well as this close method flush the buffer contents
automatically
 There is nothing like closing a decorator’s stream as it is simply providing some
functionality like buffering that it is not really dealing with some physical device like
in the case of file stream. So decorator invokes the close method of the underlying
stream.

2.2.2. Character Streams


 Character streams are used to read or write characters data like text files
 It build on top of byte streams because everything is bytes also characters are also bytes

2.2.2.1. Reader class


 It’s a base abstract class for all character input streams
 It’s used to read 16 bit characters data in UTF-16 format
 Inheritance tree for Writer characters class:
 Operations:
 Method used to read single character

o It read one character


o It return character read as integer value between 0 and 216 - 1 (65535)
o It’s quite similar to the read method of input stream class
o It return -1 if the end of stream is detected
 Method used to read group of characters

o The input array is a character array


o It read length number of characters from the input stream into the input
character array starting at index position offset
o It return total number of characters read
o It return -1 if end of stream is detected
 All read calls are blocking that is block when input data is available or some IO
exception is generated or end of stream is reached

2.2.2.2. Writer class


 It’s a base abstract class for all characters oriented output streams
 It’s used to write 16-bit character data to a destination (other destination may used
another character format something different from UTF-16)
 Inheritance tree for Writer characters class
 Operations:
 Method for writing one character to the output stream

o Input parameter is an integer which has 32bits. So the method write the
lower 2 bytes that is a 16 bits that appear on the right most and rest of the
bits are discarded
 Method used to write groups of characters

o It will write length number of characters from the input character array
starting at the index position offset

2.2.2.3. Reading Writing Text Efficiently


 The source here can be a file or socket or even a console
 File reader and file writer are used to handle files content text
 File Reader
o It used for reading characters from files
o It build on top of File input stream (it used internally file input stream). It
used this class to read or write bytes from file and do necessity to convert
from/to bytes and characters
o You can instantiated by passing file name to constructor like this

 File Writer
o It user for write characters to files
o It build on top of File output stream (it used internally file output stream)
o You can instantiated by passing file name to constructor like this

 These classes used default encoding (JVM has default encoding that is the default
character encoding of the underlying operating system its CP1252 on windows
and UTF-8 on Linux)
o To change default encoding for JVM you can use this command line
o To know what encoding your JVM uses you can use this way

o It’s not recommended to use these classes or methods because you have no
control to these configurations.
 Preferred approach: is to use these 2 classes. InputStreamReader and
OutputStreamWriter
 they enable you to set the character encoding
 these are general purpose classes for doing the translations between byte and
character streams
 input parameter of constructor are abstract input stream and output stream that is
not specific to file streams and can be passed any byte stream objects
o input stream will translate from byte to characters
o output stream will translate from bytes to characters

 example of using input stream reader with file input stream:

 File Reader and File Writer they actually extend these classes as these classes are
more generics
 to use top efficiency you would wrap them with BufferedReader or
BufferedWriter which provide additional buffering capability

 benefits of using these 2 classes is general purpose and you can set character encoding
off your choice
 Buffering:
 BufferedReader:
o use to read some character data from file using chain stream
o their constructor take input character stream any classes extends from
Reader
o Methods:
 method for reading one character ( like in Reader class): it read a
single character

 method used to read group of characters (like in Reader class): read


group of characters in the input characters array

 method used to read single line of text and return it as string: it


commonly used in real programming life
 To identify lines, the method looks to these lines separators
 \n: line feed
 \r: carriage return
 \r\n
 It return null if end of text.
 It strips new line separators.

o Reading text from File: example of using buffering reader for reading
text file which named as ‘go.txt’.

o Reading text from a console: example for reading text from console
 BufferedWriter:
o used for write some characters data to file using chain stream
o their constructor take output character stream any classes extends from
Writer

o Methods: they are like buffered reader


 Method for Writing one character ( like in Writer class ):
 Method for reading one character ( like in Reader class):
o Example for writing to a File: these is example for writing text to a file
using buffered writer

 the default buffer size is 8192 characters


 there are other constructor which can pass buffer size as input with stream
parameter
 these classes are similar to Buffer Input Stream and Buffer output stream classes
which are chained to input stream and output stream instances

2.2.3. Download webpage


 With IO package and input stream you can download web page using Input stream and
buffered input stream
 You should connect to web page before downloading data using 2 classes URL and
HttpUrlConnection
 This is example for downloading web page

2.2.4. File Class


 It can be useful for manipulating files on the system. That is you can used this class to do
things like
 Creating files and directories
 Deleting files and directories
 Renaming files
 …
 Every file or directory on the disk has a certain unique path. That is a path is used to
locate a file or directory So an instance of a file class would represent such a path and it is
instantiated as shown here
 So File class represent a path to a file or directory but not a content of the file
 File class constructor:
 File class have constructor that it take path of file or directory like string object
called pathname. Like this example

 The construction if file class does not throw an exception even if pathname is
invalid here
 We referee that file input stream and file output stream classes have constructors
which take file class as input. But the constructor that take filename as input is
more commonly used.

 Absolute basics of paths :


 Different symbols between windows and Linux:
 Double point notation (..) in path represent parent directory.

 Pathname: absolute or relative


 Absolute: it point to the same location regardless of the current working
directory. Current working directory is reefer to user directory would be a
directory in which Java interpreter is running

 Relative: its relative to the working directory


 The property user.dir system property which is accessible from get
properties method of the system class is used to get user directory.
 File class methods:
 getAbsolutePath(): this method give the absolute path of the file
 CreateNewFile (): it tries to create new file with path parameter if not exist. And
if the file is created, it return false
 File.separator: it’s a field and it gives the separator that separate directories in
pathname. Its directory separator and it return a string.
 File.separatorChar: it give the same thing like File.separator but it return a char
 getParent(): it simply return a parent of the file (the directory than contain the
file)
 LastModified (): it gives the time of last modification of file in milliseconds.
 Exists(): it return Boolean indicate if file is exist or not
 isFile()/ isDirectory(): it return if the current is file or directory
 length(): it return a size of the file in bits

2.3. Serializing Java Objects


 In some situations we need to write java objects to the disk and then in later time read
them back from the disk with the same state.
 Typically you would save object to database, but sometimes, as we will soon see
you would want to save the entire java object along with state to the disk
 The source and the destination can be other than disk like memory
 Serialization is the process of writing java object to some destination that is java object
gets saved as byte streams
 For example we need to write object A in some destination. In this case, we said
that object has been serialized
 Deserialization: Now at some point in the future we may want to reconstruct object A
from it serialize version. So deserialization is to reconstruct java objects back from their
byte streams
 These deserialization can be happen in same JVM or in other remote JVM
 Serialization process:
 To serialize an object, you need to make sure that this class implements interface
called Serializable which is marker interface from java IO package
 To do the actual serialization, and deserialization, you make use of these classes:
 ObjectOutputStream for serialization.
 It chained to Buffered output stream
 It implements ObjectOutput.
 ObjectInputStream is for deserialization.
 It chained to buffered input stream
 It implement ObjectInput
 As convention, the extension of file in that store the object is .ser. but you can use any
other extension
 You can chained object output stream to file output stream without buffered
output stream class but its recommended to use it
 Example of serialization:

 Deserialization process:
 A. First read the serialized object
 B. JVM find the serialized object’s class name and try to load the correspond class
object
 C. JVM compares the version of the loaded class with the version of the serialized
object. It should be match. Otherwise the class has evolved after the object was
serialized and they are no longer compatible
 Deserialization will fails if:
 For some raison, the class object cannot be loaded that’s for JVM could
not find the class file or for some other raison to
 Version mismatch and JVM throw an exception
 If there is no version mismatch, then JVM would create space in the heap for the
serialized object and will recreate the object with the same state. Object
constructor not run
 If there is no serializable ancestor in the inheritance tree in serialized
object then
 Ancestor constructor will be run along with any constructors of all
its direct or indirect super classes
 Instance variables will get serialized state
 Transient variable get default value
 Example of deserialization:

 Serial Version UID:


 Every serializable class has version ID computed from class structure and this
version id will stored with .class file
 Every when class structure changed, the version ID also changed
 This version ID has name serialVersionUID
 When Serialized object is generated, the object will stamped with version ID
 During deserialization, as part of version comparison...
 How can class evolve without hurting deserialization?
 Solution: make version ID constant even the class evolved
 Changes that do not affect deserialization:
 Add/delete instance variable
 Make instance variable static
 Change instance variable from transient to non transient
 Change access levels of variables
 Add/remove classes to/from inheritance tree
 Changes that affect deserialization:
 Change instance variable’s type
 Make serializable class (anywhere in object graph) non serializable
 Serialization use cases:
 Web sites that have high traffic and these are dynamic web pages: you can
serialize database objects on the disk or perform caching using ‘memcached’
 Prototyping of persistence: pretty much every object graph can quickly be made
serializable, for quick proof-of-concepts or quick-and-dirty applications this might
be faster than setting up a real ORM layer or other persistence system
 Short term storage of almost-arbitrary objects: Applications servers, for example,
have a tendency to persist session information using serialization. This has the
advantage that the values in the session can be almost any type (as long as its
serializable).
 Deployment size matters. Built into the system, so 0 extra bytes.
 All actors will use compatible versions.
 Long-term storage is not an issue.
 the most common use case for serialization is to store objects as blobs in a session
database
 Serialization facts
 Primitives variables and arrays are by default serializable:
 If an object are saved so any primitives or array fields are saved to disk
 You can pass them directly to write object of object output stream
 it save the entire object graph:
 If an object is serialized than any object it references or any object those
objects references will all be serialized
 All serialization of the original object is fails if even one objects does not
implement serializable interface
 Static variables are not serializable that’s because serialization is about object
state or static variables are class variables
 If super class is serializable then it subclasses are automatically serializable.
 If super class is not serializable but subclasses can be serializable
 If you do not want an instance variable to be serialized, then you can take variable
as ‘transient’.
 with that the variable value is skipped during serialization
 during deserialization, the transient variable get the default value
3. Collections Framework (Data Structures)
 It’s part of java.util package which includes utilities classes that mainly represent
sophisticated data structures
 Array limitations:
 An array can hold fixed numbers of values:
 It’s not automatically extendable. That’s if you want to add elements beyond the
array size then it’s not possible
 Element search is expensive. Its linear in term of complexity
 General requirement we need to have in others data structures
 No knowledge about size: be able to create data structures without specifying data
structure size
 Automatically extendable when it reaches its maximum size
 Fast random access: that mean for given index, we should be able to extract the
element of the index in constant time
 Fast lookups: that is element search should be extremely fast like constant time
 Ordered and unordered. Should be preserve the order in which the element are
added
 Duplicated and unique
 Null and non null
 Automatic sorting
 <key, value> mappings
 Collections framework include several:
 Interfaces
 Implementations of these interfaces
 Classes provide generic algorithm like searching and sorting of different data
structures
 The code interfaces and implementations of data structures in java
 Legacy implementations that are synchronized
 Vector
 Hash table
 Stack
 It’s not recommended to use them because synchronization slows things down

3.1. Collection Interface


 It’s a rout of the collection hierarchy.
 It represents a collection of objects.
 Polymophically it’s providing maximum generality. So whenever possible you should use
it to reference objects.
 Some collections like array list allow duplicates while others like set implementations do
not allow its.
 Some collections like array list are ordered while others like hash set are not.
 Collections have different sub interfaces but it has only one direct subclass and it’s called
AbstractCollection which provide scaled implementation of the collection interface.
Recall that a scaled implementation helps in minimizing the effort needed to implement
the corresponding interface
 The declaration of the collection interface:
 It extend other interface called iterable which would enable any collection object
to be used for each loops
 Iterable is from java.lang package and it has one abstract method called iterator
which subclass has to implement

 If you want instances of your class to be used in for each statement then you need to
 Implement Iterable interface
 Provide an implementation for iterator method
 Collection interface includes several fundamental methods common to all collections and
it classified into 3 categories:
 Category 1 - Basic operations :
 Category 2 - Bulk operations :

 Category 3 - Array operations :

3.2. List Interface and theirs implementations


3.2.1. List Interface
 It’s useful when sequence or positioning is matter that is preserving the order of the
element inserted is a requirement
 This interface models a resizable linear array with indexed access that is like an array
but it is resizable
 Its zero based like the array. That’s mean indexed number start from zero like arrays.
 It can also contain duplicates values
 The declaration of the List interface:
 It extends the collection interface

 In addition to methods that is inherited from collection interface. It’s also adds
several new methods
 List interface contain several new methods. These methods are classified to 4 categories:
 Category 1 – positional:
 Category 2 – search:

 Category 3 – iteration:

 Category 4 – range view:

3.2.2. Array List


 It’s an implementation of List interface
 It’s one of the most commonly used data structures
 It’s an array implementation of the List interface and it’s resizable too.
 Internally it used an array which has some characteristics:
 It obviously has some size associated with it and by default its size is 10
 When this capacity is reached a new array is created with size that is around 50%
larger than the old array size and the old array content are copied in the new array
 You can change the initial size of this array by 2 methods:
 Using constructor by passing the initial capacity as parameter

 Use method called ensure Capacity before adding large number of


elements

 Array list allow duplicates values and also nulls value


 Typical uses:
 You want to iterate list of elements like list of element fetch from database
(simple iteration of elements)
 Fast random access O(1):can access the element in constant time
 If appending element to the list or deleting last element the you can use it as both
these operations can be performed in constant time
 Some of methods in array list:
 Add and remove methods:
 add(index, element): add an element in specify index
 If the index is something other than last index, then when we add
an element all the elements following it will be shifted right by
one position
 So time complexity is linear O(n)
 remove(index): it remove an element from the specified index
 all the following elements will be shifted left by one position
 time complexity is linear O(n)
 search : contains and indexOf
 contains method would return true if the specified element is present in
the array list
 indexOf method return the index number of the specified element in the
array list if the specified element is present in the array list and it would
return -1 if the element is not present
 all these methods scan the array list from the beginning of the list
 All these methods complexity is linear O(n) that is when specified element
happens to be the last element in the list then the entire list is scanned
 These methods use equals() method to compare the input element with
each of the elements in the list (recall equals method is from Object class
and it can be overridden by any subclass)
 If there are frequent searches the go with the set implementation (for example
Hash Set can search an element in constant time).
 removeAll(collection): it removes all the elements in the current list which are
also present in the input collection. Intern of the implementation:
 it invokes the contains method of the input collection object for each
element in the array list
 if element is present, the it use the remove method of the array list
to remove the element
 it complexity can be worse than O(n*n) quadratic for this reason:
 retainAll(): some performance issue than removeAll method
 Constant time complexity methods O(1):
 size method
 isEmpty method
 set() and get() methods
 iterator and listIterator method

3.2.3. Linked List


 In the word of data structures there are 2 types of linked list:
 Simply linked list: this type is unidirectional. From element we can get the next
element

 It has list of elements with the elements are linked


 Each element is called as Node
 A node has 2 components
 Data: it’s a real data
 Pointer: it’s a pointer to the next node
 The last node is not linked to any other node and hence the next reference
is set to null
 The first node is called the Head node
 It doesn’t have any data. It’s simply connect to the first node (or
last node)
 In java, we can have this kind of class call Node which has 2 variables:
 Data: for example just integer data
 Pointer to the next node: data type is Node class

 Finally this is the format of our linked list class


 Doubly linked list: this type is bidirectional. From element we can get the next
element and the previous element.

 Each element in doubly linked list has 2 links


 Linked to the next element
 Linked to the previous element
 Like simply linked list, doubly linked list has head node which linked to
the first and the last node
 There are couple of properties:
 If you add new element it get added right before a head (at the last
of the list). In this case is element 2
 Head linked also to the zero element( first node in the list)
 If you should access one element from one index you need to traverse all
half of the list
 You need to know the index is closed to the first element or the last
 After that you need to traverse all half list from the choose between
first or last element
 This is steps for building doubly linked list:
 First we has head node only which next and previous point to itself
because there are no other element
 When we added an element, a new node was created
 We should point the next and previous pointer for head to the new
node

 You would want to use linked list if you iterating and during the iterating if you
have frequent add/remove operations you would go for it. Because in linked list
when you would add/remove element. It’s just linked with correct way
 Its better data structure for remove all or retain all operations
 These are more methods if linked list which have linear time complexity
O(n)
 Get(i): n/2 operations
 Add(i,e) : n/2 operations
 Remove(i) : n/2 operations
 indexOf(Object)
 lastIndexOf(Object)
 Java support only doubly linked list
 A linked list is basically a doubly linked list implementation of List and
Deque interfaces
 Because it models LIFO and FIFO operations in constant time O (1).
 It also allows duplicates and nulls values

3.3. Iterator and ListIterator


 Iterator helps in iterating elements
 An iterator is simply an interface and to access an instance of iterator we need to invoke
the iterator method which is declared in the Iterable interface

 Collection interface extends the iterable interface


 Collection implementations like array list implements the iterator method
 By extending iterable, collection interface is saying that its elements can be
iterated (for each statement request any object it iterate to implements iterable
interface)

3.3.1. Iterable interface


 Iterable interface has 3 methods like picture:
 Iterator method:
 its abstract method
 it return an iterator which can be used for iterating the elements of the
collection
 internally forEach statement loop also invoke this method for iterating the
collection elements
 forEach method:
 its default method which added in java 8
 it can be invoked if you want to perform certain action for each element of
the collection
 this action would be a method in an object which is passed as input to the
method
 the action method would be have single parameter
 We should passed one of these 3 expressions :
 An instance of consumer which implements accept method

 Lambda expression (vue in other chapter)


 Method references (ClassName::MethodName)

 Consumer is an interface introduced in java 8 and it has single abstract method


called accept
 spliterator method:
 its default method which added in java 8
 it can be used to partition those elements and process those partitions
through some parallel competition
 its mainly useful for splitting the elements of collection into partitions, and
we can process those partitions using separate threads.
 The interface provide default implementation for these last 2 methods (for each and
spliterator )

3.3.2. Iterator interface


 The iterator interface:
 If you invoke iterator method of array list, it returns an instance of this interface
(array list has nested class which implement this interface)
 If you want to range all element in for /forEach loop, you need to implement
iterable method to you object like this:
 It used to iterate elements of the collection but addition it also let you remove an
element during their duration by using remove method from iterator interface
when you range all element of list in loop statement.
 Structural modification = add or remove
 All the implementations of collection interface when they are iterated in loop
statement( like for/forEach statement), they will throw
ConcurrentModificationException when we try to add or remove element in loop
statement like this example:
 forEachRemaining method is similar to forEach method in the iterable interface

 methods for iterator interface:

3.3.3. List Iterator


 Its specific to only List and it extends the iterator interface and have some additional
functionality
 If you recall, we have briefly mentioned about these 2 methods that list interface provide
 All these 2 methods return an instance of list iterator
 Second one return list iterator starting from particular index in the current list

 List iterator interface:


 It extend iterator interface and provide additional functionality
 With iterator we can
 Only remove element
 But using list iterator we can additionally :
 Add elements
 Replace elements
 Iterate both forwards as well as backwards (support bidirectional access)
 To support bidirectional access, we have 2 methods to forwards (hasNext and next
methods) and additionally we have 2 methods for backwards (hasPrevious and
previous methods)
 hasPrevious method simply return Boolean if the current element has previous
element or not
 Previous simply return the previous element
 We have also nextIndex and previousIndex which give the index number of the
next or previous element
 Remove method would remove the element that was returned by the immediately
preceding cone which has to be either next or previous. Otherwise an illegal state
exception will be thrown
 In iterator interface we can also remove the next iterator only …
 Set method will update the last element returned by next or previous otherwise
will return illegal state exception if the immediate preceding call is not next or
previous or set method (for only set method, the preceding call wil be
next/previous or set method)

 The immediate preceding call for set method should be : next/previous/set


methods otherwise will return illegal state exception
 The preceding call for remove or add method should be: next/previous/set
methods otherwise will return illegal state exception
 Cursor position:

 The cursor is between 2 elements it means that there is no concept of current


element with list iterator that’s a reason we have method like next index, next,
previous index and previous so there is no current index in list iterator
 When we start the iteration, and when we invoke next index it would return
zero
 Similarly when we invoke previous index at start of iteration it would return -1
 When we invoke next index when cursor at the end of the list then the size of
the list would be returned
 When we invoke add method, then new element will added after the previous
calling of next/previous method and the cursor is after the added element

3.4. Queue Interfaces


3.4.1. Queue Interface
 It’s useful when we need to manipulate head and tail
 Head been the first element
 Tail been the last element (it’s the element which added most recently)
 Using queue interface we can :
 Added element to the tail (end of the list)
 Remove or retrieve from the head (retrieve is mean the element was returned and
not removed from the queue)
 Its represent the modeling FIFO (First In First Out) that’s mean the element was added
first is the element was removed first
 Queues can contain duplicates
 Queues can have nulls values but generally most queue implementations don’t support
nulls
 Recall linked list which also a queue allows null values
 Queues do not support index base access to its elements
 Generally queue are frequent used compare to less
 In additions to methods inherited from collection interface, it also added new methods
which are specific to head and tail manipulation

3.4.2. Deque Interface


 Its sub interface of queue
 It simply shortcut for double ended queue which means that element can be added and
removed at both the end of the queue
 Its represent the modeling FIFO (because extends queue) and LIFO ( because its double
ended queue)
 We have many implementations of deque interface:
 ArrayDeque: it’s the most commonly used implementation
 LinkedList:
 ConcurentLinkedDeque:
 LinkedBlockingDeque:
 Deque introduce new names for head and tail which are first and last

 There are many additional methods added by deque interface:


 Add(e)/offer(e): add element to the tail of deque (inherited from queue)
 addList(e)offerLast(e): add element to the tail of deque
 removeLast(e)/pollLast(e): remove element from the last/tail of deque
 getLast(e)/peekLast(e): get last element (tail element)
 remove/poll: remove element from the head of deque (inherited from queue)
 element/peek: get the head/first element of deque (inherited from queue)
 removeFirst/pollFirst: remove the head/first element from the deque
 getFirst/peekFirst: get the head/first element from the deque
 addFirst/offerFirst: add element to the head/first of deque
 deque also support some additional methods whose names represent stack operations
 push: it’s same as addFirst(e)
 pop: it’s same as removeFirst

 there are other methods offer by deque interface like:


 removeFirstOccurence(object):it take an element as input and would remove the
first occurrences of that element
 removeLastOccurence(object): it take an element as input and would remove
the last occurrences of that element
 BlockingQueue: there are also something called blocking queues where operations can
block
 For instance, if you want to add an element into the queue and if the queue is full
(pleine) then the operations would wait until some spaces available
 Similarly a remove operation would wait if the queue is empty and it would great
until an element gets inserted
 We will look blocking queue implementations in the concurrency chapter as it
will be helpful for inter thread communication

3.4.3. Array Deque


 It’s an array implementation of deque interface and it’s resizable
 Internally it uses an array just like an array list
 It was added in java 6 which means that it’s a fairly new data structure
 Since it’s a deque, it’s an implementation for models FIFO and LIFO.
 Unlike a linked list which is also deque,
 Array deque prohibits null value. So you cannot add null values
 It does not implement List interface

 There are many constructors for creating an array deque:
 Default constructor (without any input parameters):

 Constructor with Integer parameter: you can specify a fix capacity by add
integer parameter which represent size of deque

 Constructor with collection parameter: construct the array deque with the
elements from the collection parameter added

 Its recommended to use array deque then linked list because many reasons:
 From java doc: array deque is faster than linked list if the linked list is used as a
queue
 Array deque is around 3 times faster than linked list for large queue. The main
reason for that is with linked list we have to create an additional null object with
every newly added element (array deque is more memory full deque)
 Why can’t use array list like a FIFO? We simply need to use add method for adding
element to the tail and remove of zero for removing element from head
 Performance:
 Invoking remove of zero on an array list would shift all the subsequent
elements so it has linear time complexity
 Gets bad with large number of elements because we have more and more
elements shifts
 For example for 1000 elements, linked List is 20 faster than array list for queue like
access
 With array deque we don’t have elements shifts as its implementation is
base on something called circular array which does not evolve elements
shifts. It could constant time for adding and removing instance
 Intention:
 Intention when using array deque is too used as FIFO or LIFO which
involve only head or tail manipulation.
 Methods like pop peak and push very clearly referent that
 But with array list, do not constrain ourselves to only head and tail
 Methods complexity:
 Most methods run in amortized constant time that is mostly constant time
 Some methods for removing or searching specific objects would be linear
complexity as we need to scan the queue like:
 Remove object (it’s not remove head element)
 Remove first concurrency
 Remove last concurrency
 Contains

3.5. Hash Table


 It support some really fast operations like searching of elements
 Both hash map and hash set are base on hash table
 It’s a fundamental data structure that is used to implement an associative array which
associates keys with values
 It’s an array where each element is basically an association between a key and a value
 Its collection for key value pairs

 Each key value pair is also referred to as a mapping and hash table is also referred to a
dictionary.
 Key operations: all these operations happen in a constant time so hash table is really fast
 Insert key value mapping into hash table
 Searching mapping using given key
 Remove particular mapping by using a key
 Hash table characteristics:
 It cannot contain duplicate keys
 It can contain duplicate value
 Each key maps to at most one value
 There are certain implementation allow null value but also allow one null key. But
some others implementations do not allow nulls for both keys as well as values
 Illustration of hash table is implementation:
 Its associative array
 We have array and each element of these array is referenced to linked list which
stored the actual key value mappings
 The array does not store the key value mapping but the linked list is store that
 Each linked list can have multiple mapping to
 For each key value mapping there are function called hash function is applied on
the key and the result is the value in the array (for that we can have many
mapping in same linked list)

 Hash function:
 It’s basically a function of the key and the array size
 The simple function of hash function is key mod array size
 Its quickly locate the target for this it should be highly efficient
 It should be able to dispose the elements as uniformly as possible into the buckets
 Inserting operations (separate chaining):
 Just look at the bucket for a given key by using hash function and we check if the
bucket is empty
 If the bucket is empty then we create new linked list in that index and add
the mapping into that linked list
 If bucket is not empty (means there is collision which means many
mapping in some bucket) then we check if linked list has another mapping
with same key
o If there is no such mapping then the mapping is added at the front
of the list
o If there is mapping with same key then value in the old mapping
is overwritten using the new value
 So here we have collision and we are using collision resolution strategy called
separate chaining
 Others factors besides a good hash function that contribute to performance:
 Capacity: number of bucket in the hash table. Default is 16
 Load factor: how from the hash table can get before its capacity is automatically
increased. Default load factor is .75
 Resizing hash table is involves expansive rehashing because when we resize hash table
we should change all buckets of all intern inked lists.
 When you have very large numbers of mappings, so you should create new hash
table with very large initial capacity
 If you used very high load factory then you may have less frequently hashing but you
have lot of collision too and that can slow things
 If you have very large numbers of mappings, then you should have some
experiments to choose the right factor
 Applications of hash tables:
 Database indexing:
 NoSql databases: because it store key value mapping
 Switch statement: internally it used hashing to quickly look at matching case
blocks

3.5.1. Hash code (method of Object class)


 This method is used by Hash function of Hash table class
 It returns a hash code value for the object. This method is supported for the benefit of
hash tables such as those provided by HashMap.
 The general contract of hashCode is:
 Whenever it is invoked on the same object more than once during an execution of
a Java application, the hashCode method must consistently return the same
integer, provided no information used in equals comparisons on the object is
modified. This integer need not remain consistent from one execution of an
application to another execution of the same application.
 If two objects are equal according to the equals (Object) method, then calling the
hashCode method on each of the two objects must produce the same integer
result.
 It is not required that if two objects are unequal according to the
equals(java.lang.Object) method, then calling the hashCode method on each of the
two objects must produce distinct integer results. However, the programmer
should be aware that producing distinct integer results for unequal objects may
improve the performance of hash tables.

3.5.2. Equals method (method of Object class)


 Indicates whether some other object is "equal to" this one.
 The equals method implements an equivalence relation on non-null object references:
 It is reflexive: for any non-null reference value x, x.equals(x) should return true.
 It is symmetric: for any non-null reference values x and y, x.equals(y) should
return true if and only if y.equals(x) returns true.
 It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns
true and y.equals(z) returns true, then x.equals(z) should return true.
 It is consistent: for any non-null reference values x and y, multiple invocations of
x.equals(y) consistently return true or consistently return false, provided no
information used in equals comparisons on the objects is modified
 For any non-null reference value x, x.equals(null) should return false.
 The equals method for class Object implements the most discriminating possible
equivalence relation on objects; that is, for any non-null reference values x and y, this
method returns true if and only if x and y refer to the same object (x == y has the value
true).
 Note that it is generally necessary to override the hashCode method whenever this
method is overridden, so as to maintain the general contract for the hashCode method,
which states that equal objects must have equal hash codes.
 Item 9: Always override hashCode method when you override equals
method
 When you refer to objects by their interfaces you can change their
implementations in any time by couplage faible
 If you want to treat 2 different objects as logically equal you must override
booth equals and hash code methods
 If you are overriding only hash code method, was not helpful in preventing that
duplicate from getting added.
 If only equal was overridden but not hash code method then it’s very likely
that that duplicate object will be stored in completely different packet

3.6. Set Interface and theirs implementations


3.6.1. Set interface
 Set interface extends the collection interface
 It models a mathematical set. Which mean like linked list, a set cannot have duplicates
 It’s useful when
 Uniqueness matters
 Fast lookup matters
 Insertion order does not matter (it’s not like list interface which theirs element
position is a criteria that is insertion order is important).
 But was matter in set interface is fast lookups and uniqueness
 Sort Set (implementation of Set interface):
 Sort Set is a sub interface of set and it get additionally be useful for sorting the
elements
 In additionally to uniqueness and fast lookup, sorted Set will also help with
sorting the elements
 Set interface does not have any new methods on top of what it inherits from the collection
interface
 However due to the fact that it does not allow duplicates it just places additional
requirements on some of the inherited methods and also the constructors
 For example for add all method it explicitly states that duplicates are not allowed.
3.6.2. Hash Set (Item 52)
 Hash set is based on hash table as it internally uses hash map
 It’s a hash table based implementation of a set interface
 Internally it use Hash map which store key value pairs.

 Key: hash set stores only individual objects those objects will be stored as keys
 Value: an empty object will be stored as value (the empty object is an instance of
object class)
 You can show add method of class Hash set if you are interested
 It also allows one null value
 Typical use case: it is useful when the needed is
 Rapid lookup, rapid insertion and rapid deletion O(1)
 Insertion order is not important
 Its better then array list if removeAll or retainAll operations are to be use
frequently.
 In array list each invocation of remove all method will be index all
elements and remove elements So its complexity is linear O(n)
 In hash set, complexity of remove all or retain all has constant complexity
O(1)
 Item 52: Refer to objects by their interfaces
 Its recommended when you create an object to refer to their objects by their
interface like this example

3.6.3. LinkedHashSet
 It’s another set implementation
 It uses a hash table as well as a linked list in its implementation of the set interface
 Linked hash set has many characteristics:
 Preserves insertion order (using double linked list):it has a doubled linked list
running through its elements which helps in preserving the order of inserted
elements
 It extend Hash set so its almost as fast as hash set
 Like hash set, rapid lookup insertion and deletion has constant time O(1)
 It permit only one null element
 Internally it used LinkedHashMap
 All set implementation uses internally their corresponding map implementation
 Use LinkedHashSet if you want:
 Fast lookup insertion and deletion
 Insertion order is important ( is preserved )
 Better then array List if remove All and retain All operations are to be used frequently
 When you want to iteration the elements, LinkedHashSet is faster than Hash Set.
That’s because:
 Iteration with LinkedHashSet is dependent on the size of the set due to use
of double linked list
 Iteration with Hash Set is dependent on the capacity (its number of
buckets in the Hash Table that is the array size)

3.6.4. Sorted Set interface


 It’s a sub interface of Set interface
 Sorted Set additionally provides to all others set implementations the sorting capability
 Sorting is a very important feature of any application. Whenever we have list of items
then we need to be sorted is some order
 Sorted set extends from set interface.

 It declare many important methods in many categories:


 Range view:
o Sub Set method:

 It returns a sorted set which contain the elements between


parameters (from Element and to Element). It returns a sub set of
the original set.
 Any change made in return set will be reflected in the original set
 Any changes made in original set will also be reflected in the
returned set.
 Returned set throw illegal argument exception if you try to insert
an element into that set and if that element is outside the range of
the return set.(outside range of ‘from Element’ and ‘to Element’)
o Head set method:

 It returns a sorted set that includes elements that are less than the
input argument ‘to element’.
o Tail set method:

 It returns a sorted set that include elements that are great or equal
to the input argument ‘from element’.
 End points:
o First method:

 It returns the first element in the sorted set


o Last method:

 It returns the last element in the sorted set


 Comparator access:
o Comparator method:

 It returns comparator class which will discuss in tree set class


 Comparator class is something that helps in keeping the elements
of the set sorted.
 If comparator is not use then null value is returns which would
indicate that a default ordering or natural ordering is used for
sorting the elements
o Spliterator method:

It discuss in iterator lesson


It used for splitting the elements of the collection into partitions so
you can process these partition using separate threads.
 In additionally to these methods, it has methods inherited from set interface

3.6.4.1. Navigable Set


 It’s a sub interface of sorted set interface

 It’s also a sorted set and its implemented by Tree set


 In additionally to methods inherited from sorted set, navigable set has many others
methods in many categories:
 Closest matches
o Lower method:

 It return the greatest element that is less that the target element E
which is the input to the method
 greatest element < E
 It would return a null if no such element would be fun.
o Floor method:

 It’s similar to lower method but it returns the greatest element that
is less than or equal to the target element E
 greatest element <= E
o Ceiling method:

 It returns the lowest element greater than or equal to the target


element E
 Least element >= E
o Higher method:

 It returns the lowest element greater than target element E


 Least element > E
 Example:

 Iterators:
o Iterator methods:

 Iterator method:
 It return iterator class for regular iteration
 Descending iterator method:
 It return iterator class for iterating in the reverse order
o Descending set method:

 It simply returns the reverse view of the original set


 End points

o Pool first method:


 It remove the first element and also return it
o Pool last method:
 It remove the last element and return it
 All these methods return null value if the set is empty
 Range view:
o Head set method:
 It like sorted set method, it returns a sorted set that includes
elements that are less than the input argument ‘to element’.
 If Boolean input is:
 True: than it returns set that includes elements that are less
than or equal to the input argument element
 False: than the input argument element would be excluded.
So it return elements that are less to the input element

3.6.5. Tree Set (Comparable Comparator)


 It uses a tree data structures.
 It’s a red-black tree based implementation of navigable set interface
 It has many characteristics:
 Internally it uses Tree Map just like away Hash set uses Hash map
 It stores (key, value) pairs. But tree set has only element So it stores:
 the elements as keys
 an empty object that is an instance of object class as the value
 Tree set elements will be
 Unique: because it’s a set
 Sorted: because it’s a sorted set
 Its slightly slower than hash set it still offer fast lookup with log complexity for
add/remove/contains methods O(log(n))
 tree set implementation should use one of these approaches to sort their elements
 Implement Comparable interface
 Create new class which implement Comparator interface and passed to
Tree set class
 If you don’t passé class implement comparator interface or their elements don’t
implement Comparable interface then when you invoke add method, it will
generate exception:

 Example of creating tree set of strings:

 Comparable – Comparator: Elements in Tree set should be sorted in certain order. So


there are 2 ways to do it:
 Natural ordering: implement interface called java.lang. Comparable.
 Java Comparable interface is used to order the objects of the user-defined
class
 You need to implement this interface
 It has one method called compare To: it basically returns an integer value
(zero, positive, negative)

 Tree set implementation is going to invoke compare To method on the


new element they want to add and it will pass for each element exist in the
set. If returns:
 Zero: so its duplicate value and will not added
 Negative integer: new element has to be placed before the input
element
 Positive integer: it needs to be placed after the input element.
 Use Comparator interface:
 It has method called compare method which compare 2 objects passed to
method like input parameters
 It takes 2 objects and it compares them
 The only abstract method in Comparator interface is abstract method
 Tree set implementation will invoke compare method
 When we need comparator we need to be implemented in separated class
3.7. Map Interface and theirs implementations
3.7.1. Map Interface
 It’s a second inheritance tree in the collection framework
 It’s the root of map hierarchy
 It has many characteristics:
 It store key value pairs. And it’s useful for fast lookups by keys.
 Map implementation like Hash map is also refers to as an associative array
 It cannot have duplicate keys but duplicate value are fine
 Each key maps to at most one value
 Some map implementations allow only one null key and other don’t allow ant null
keys at all
 Similarly null value maybe allows and maybe not
 Like case of collection maps also comes with skeletal (squelette) implementation
called Abstract Map. So implementation like Hash map extends this particular
class
 It does not extends iterable interface but theirs elements can be iterated
 Declaration of map interface:

 K: is the class which represent the type of all keys in the map
 V: is the class which represent the type of all values in the Map
 it has many types of operations (many type of methods)
 Basic operations:
 Put method:
 It simply add the key and value pair into the map
 If there is already map with the same key then the value in that
mapping will be overwritten with the new value. Also the old value
will be return with this method
 If there is no mapping with that key then the new mapping will be
inserted and the null value will be returned
 But if the map implementation allows null value and there is
matching key with the null value then that null value will be
returned
 get method:
 it returns the value corresponding to the given key
 if there is no mapping with that key, then a null is returned

 remove method:
 it remove a mapping for the input key and it returns the
corresponding value
 it would return null if the mapping with matching key was not
found

 contains value method:


 it return a true if the map contain the specify value

 contains key method:


 it returns a true if the input key is present in the map

 size method:
 it would return a size of the map

 is empty method:
 it return a true if the size of the map is zero which means it is
empty

 Bulk operations:
 Put all method:
 It would add all the mapping from the input map into the current
map
 It’s similar to the add all method in the collection interface
 Clear method:
 It simply remove all the mappings from the map

 Collection view operations:


 Key set method:
 If you want to view all keys present in the map
 This method would return a set contains all keys present in the map
 If you want to remove element present in the return set, you can
invoke the iterator method on the return set and then you can
invoke the remove method on the return iterator
 You can use all methods to the return set except add /add all you
cannot used.
 And if you invoke add or add all method, you will get unsupported
operation exception
 Any changes made in the return set, will be reflected in the original
map and vice versa

 Values method:
 It would return collection view of all values in the map
 All properties we discussed to the key set method, will also for this
methods

 Entry set method:


 It can be used for iterating the map
 It returns a set view of all the mapping in the map and each
mapping is an instance of inner interface called Entry.
 Each instance of entry corresponds to mapping in map and so it
stores both key as well as values.
 In map interface or all map implementation, keys type should be immutable.
 Because if you start mutable keys and then later you change the state. Then when you
search for the same key the map may return null value. For instance like hash map
which use hash function. It may get different value (value of hash function of start key
was different to hash function of the key after change).
 There are 2 way to iterate mapping instance:
 Using key set method:

 Using entry set method:

3.7.2. Hash map implementation


 Its implement map interface.
 Methods get put and remove have constant time complexity.
 In hash map insertion order is not preserved as the elements are stored based on using
hash function
 It permits null values and also one null key
 Its methods are not synchronized unlike the legacy hash table class. If synchronization is
required, it can always be taken care of externally

3.7.3. Linked Hash Map


 Linked hash map extends hash map
 Similarly to hash set and linked hash set, the map implementation’s hash map does not
preserve insertion order will linked hash map which extends hash map does preserve
insertion order without much difference in the speed
 It’s basically hash table as well as linked list implementation of Map interface
 It has double linked list running through entries which help in preserving the
order of inserting mappings
 It extends hash map and so it almost as fast as hash map
 Lookup, insertion and deletion operations are supported in constant time
 It permits null value and also one null key
 Its methods are not synchronized just like in the case of hash map
 Iteration speed of linked hash map: Linked hash map is slightly faster than hash map in
iteration operations because many things:
 Iterations with linked hash map is dependent on the size of the map due to use of
double linked list
 But case of hash map iteration is dependent on the capacity
 Linked hash map can be used as an LRU cache (very important feature of linked hash
map) where LRU stands for least recently used
 Cache is basically a component that stores important data.
 These important data can be quickly access
 When you say important it could means:
 Anything depending on the application context
 most recently used items
 most frequently accessed items
 most liked or most shared items like face book
 memcached is very popular in memory caching system that lot all of web sites
use them
 illustration of LRU cache:

 it use least recently used caching strategy


 on running of the cache we have least recently used item and in other
hand most recently used item.
 items are ordering on how recently they were used
 if we add an entry to the cache that would be considered as the most
recently used item and it would be added on the end like most recently
used item
 if the cache is full, the new entry will be added and the least recently
added entry on the other end would be removed
 If an entry in the cache is accessed then that entry will be moved to the
end which represents most recently access item. Any item become before
that access item are shifted by one position
 if you are searching to an item and if this item is found in the cache then
we said that we have it cache hit
 if the item is no found in the cache then we say that we have cache miss
and we try to found that item in the database and if found it would be
moved to the cache.
 This LRU cache is feature of only linked hash map

 How to allow use linked hash map as LRU cache:


 To allow linked hash map as LRU cache, you need to use this
constructor by passing true to the last argument

 If you want fixed size for LRU cache, you need to extend this class and
then you can specify the size of LRU cache

 To remove the least recently used item there is this method called
remove eldest entry.

 When insert item using put method or put all method that would
invoke this particular method.
 In this class this method was always return false. If it return
false that means the eldest entry should not be removed by
invoking remove eldest entry at put and put All methods
 By default the linked hash map that not removed the eldest
entry because we should remove eldest entry if the size is full
and linked hash map has unlimited size
 To remove the eldest entry, you should extends this class and
override this method and if the size is full
3.7.4. Sorted Map
 Sorted map allows sorting of mappings base on keys
 this sorting of sorted map can be either due to
 natural ordering: it means keys would implement comparable interface
 comparator interface which provided during the creation of map
 sorted map implement map interface so it inherit theirs methods

 sorted map methods have many types like (theirs methods are very similar to methods of
sorted set):
 range view:

 sub map: it return map contain all mappings between “from Key” and
“to key”
 head map: it return map contain all mapping between the first key an
“to key”
 tail map: it return map contain all mappings between “from key” and
the last key
 end points:

 first key method: it return first key of the map


 last key method: it return the last key of the map
 comparator class:
 Comparator method: it return the comparator class if there is one.
Otherwise implying that a natural ordering is used

 collection view operations:

 key set method: it return the set of all keys ordered according to the
sorting criteria
 values method: it return collection of values in the sorted map and the
order of values is depending on the corresponding keys
 entry set method: it return a set of all the mapping in the sorted map and
also they are sorted by keys

3.7.5. Navigable Map


 Navigable map extends sorted map
 It analog navigable set which included navigation methods.
 Methods for navigable map is like this (is similar to navigable set which you can see
them signification):

3.7.5.1. Tree Map implementation


 Its implementation of navigable map interface so it implement all their methods

3.8. Arrays Class


 It’s a generic utility class and it help us in manipulating an array through its various
methods
 It has methods which can help us convert an array to array list
 similarly it also has method that can help as sort an array or search element in an array or
even make copy of an array or compare 2 arrays to see how has identical contents
 it has lot of useful utilities methods
 in java 8 it has several new methods which help which support parallels operations have
been added to this class
 it’s from java util package
 sequential methods:
 As list method:
 It converts from array to array list collection.
 It take as input array and it return a list
 The returned array list has fixed size: you cannot remove an element or
you cannot add an element. If you try to do that, the return array list will
throw an error. But you can update the value

 If you want to the returned array list to be modifiable, the you can do something like
this

 You can pass dynamic parameters (coma separator list) to as list method
and it return array list of these input parameters

 You can create array list with fixed size using as List and Array list class
by passing to as list method Array not initialized like this example

 To string method: it takes an array and will return a string representation of all
the elements. Returns a string representation of the contents of the specified array.
The string representation consists of a list of the array's elements, enclosed in
square brackets ("[]").

 Sort method with natural ordering:


 this method is takes an object array
 it returns a void and this particular method uses merge sort with natural
ordering which means that the array elements should have implemented
Comparable interface
 if array is partially sorted then far fewer than nlog(n) comparisons
 if array almost sorted then approx n comparisons
 if you have 2 or more arrays which are already sorted, then the very way merge them
for sort them is concatenate them and then sorting the result array because they are
partially sorted so we have the much faster way to sort the merged array
 sort method with custom ordering:

 it’s another version of sort method which takes array and comparator
implementation
 binary search method:
 it takes like parameters an array and the search item
 it uses binary search algorithm it’s used for search the second parameter in
the first input array
 the input array must be sorted otherwise the behavior is undefined
 if the element in found, it would return the index in the array
 otherwise it look at the index position where this element can be inserted
by resting the array sorted and it returns –(insertion point) – 1

 copy of method:
 it takes an array and length of the new array and it return copy of the input
array with specified length
 if the input length greater than the input array, then it would copy all the
elements of the array and for all the remaining slots it would ad zero

 fill method:
 It basically takes an array and input parameter and fills (remplir) each
element from input array by second input parameter.
 That’s a good way to initialize an array with only one element

 Equals method:
 It basically takes 2 arrays and would
 It return true if the 2 input arrays are equals which means the arrays are the
same type, the same size and they have the exact same contents
 Deep equals method:
 It’s also equal method but it does deep equals which means if we have
nester arrays the it would still be able to compare the array
 It not accept not single dimension only but also multi dimensions arrays
 Because one single dimension is an object but this method accept
an array of object (for example Integer[] is an object not array of
object)
 It takes like parameter 2 arrays of Object class
 It returns true if arrays are deeply equals to one another
 Deeply: is more appropriate for nested arrays

 Parallelized Operations (from Java 8): it used if your system has multiple cores then
those methods can those cores in order to parallelism and efficiently
 Parallel sort method:
 It just like a sort method it takes an input array and it sort the elements
 This method is beneficial only if large arrays ( more than 8192 element)
 If the input array has size more than 1 >> 13 = 8192 it used multi core
system and it would be faster
 If the input array has size less than 8192, it would use the sequential sort
method

 Parallel prefix method:


 It would cumulates each element of the array which means if you have an
array like this [2, 1, 0, 3] then the return array [2, 3(= 2 + 1), 3( = 0 + 1 +
2), 6( = 3 + 0 + 1 + 2)]
 It takes 2 parameters one is an integer array and the second is
IntBinaryOperator implementation like lambda or reference method or
class implementation
 Parallel set all method:
 It takes 2 parameters first is integer array and second is functional
interface : IntUnaryOperator implementations
 It basically sets each element in the input array to some value

3.9. Collections Class


 It’s from java util package
 It used to manipulate al different types of data structures
 It’s utility class with many static methods and it help us in doing stuff like sorting
searching
 There is many utility methods in collections class:
 Add all method:
 It takes as input collection and array
 it would add all elements from input array to the input collection
 it’s like using as List method in arrays class

 sort method:
 it just identically to sort method in Arrays class
 it would just sort the elements of an input list
 in this case the parameter is just a list
 it would use natural ordering to sort the elements of the list which means
the elements of the list must implement comparable interface

 binary search method:


 it takes couples of list and key and would search the key in the list using
binary search algorithm
 it return index if the key is found
 The input list needs to be sorted. If it is sorted then it would be log(n)
complexity
 if not sorted, the results is undefined

 reverse method: it would reverse the elements of an input list

 swap method:

 frequency method: it look at input parameter and tell how many time it present
in the input list

 shuffle method

 max/min method: return the max/min value from input list using natural ordering

 Check out others methods in API


 Item 43: Return empty arrays or collections, not nulls
 If your method returns a collection or an array and if the method has not any
things to returns then it should return an empty collections/arrays but not null
value
 If you return null value, then
 you have extra code, for example test in the client if return list/array is null
or not like this example
 client forgetting null check: error might go unnoticed for years

 Solution: return empty array or collection


 It’s expensive to create empty array or collection??
 You can use Collections.emptyList() method to return empty collection

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy