Upload
ionela-teclea
View
230
Download
0
Embed Size (px)
Citation preview
7/25/2019 Basic Programming Session 4
1/17
endava.com
QUALITY. PRODUCTIVITY. INNOVATION.
Basic Programming
Session 4
7/25/2019 Basic Programming Session 4
2/17
2
Basic Programming
Garbage collection
String & StringBuilder
toString
Collections ArrayList
HashSet
HashMap
Q & A
QUALITY. PRODUCTIVITY. INNOVATION.
7/25/2019 Basic Programming Session 4
3/17
3
3
Memory management and Garbage Collection
QUALITY. PRODUCTIVITY. INNOVATION.
Memory management
Garbage collection is a way in which Java recollects the space occupied
by loitering objects.
In general, a garbage collector is responsible with three tasks:
Allocating memory for new objects
Ensuring that any reference objects (live objects) remain in
memory
Recovering memory used by objects that are no longer reachable(dead objects)
WhenDoes the Garbage Collector Run?
How Does the Garbage Collector Work?
7/25/2019 Basic Programming Session 4
4/17
4
Reassigning a Reference Variableset the referencevariable to refer to another object.
class GarbageTruck {
public static void main(String [] args) {
StringBuffer s1 = new StringBuffer("hello");
StringBuffer s2 = new StringBuffer("goodbye");
System.out.println(s1);
// At this point the StringBuffer "hello" isnot eligible
s1 = s2; // Redirects s1 to refer to the"goodbye" object
// Now the StringBuffer "hello" is eligible for
collection
}
}
Nulling a Reference - set the reference variable
that refers to the object to null.
public class GarbageTruck {
public static void main(String [] args) {
StringBuffer sb = new
StringBuffer("hello");
System.out.println(sb);
// The StringBuffer object is not eligiblefor collection
sb = null;
// Now the StringBuffer object is eligiblefor collection
}
}
Writing Code That Explicitly MakesObjects Eligible for Collection
QUALITY. PRODUCTIVITY. INNOVATION.
7/25/2019 Basic Programming Session 4
5/17
5
5
String
The String Class
KEY concept: once a String object is created, it can never
be changed !
Immutable Objects
QUALITY. PRODUCTIVITY. INNOVATION.
Step 1
String myString = Hello;
Step 2
String secondString =
myString;
Step 3
myString =
myString.concat( World)
The heap
HellomyString
(reference
variable)
The heap
Hello
myString(reference variable)
secondString
(reference variable)
The heap
Hello
myString(reference variable)
secondString(reference variable)
Hello World
7/25/2019 Basic Programming Session 4
6/17
6
6
Important Methods in the String class
QUALITY. PRODUCTIVITY. INNOVATION.
7/25/2019 Basic Programming Session 4
7/17
7
7
toString()
Implementing toStringmethod in java is done by overriding the Objects toString method.
The java toString() method is used when we need a string representation of an object. It is defined inObject class. This method can be overridden to customize the String representation of the Object.
Demo
Conclusion
Since our example has no toString method, the default one in Object is used. The format of the defaulttoString method of the Object is as shown below.
Class Name, @, and the hex version of the objects hashcode concatenated into a string.The default hashCode method in Object is typically implemented by converting the memory address of theobject into an integer.
QUALITY. PRODUCTIVITY. INNOVATION.
7/25/2019 Basic Programming Session 4
8/17
8
8
The StringBuffer and StringBuilderClasses
The java.lang.StringBuffer andjava.lang.StringBuilderclasses should be usedwhen you have to make a lot of modifications to strings of characters.
The StringBuilderclass was added in Java 5. It has exactly the same API as the
StringBufferclass, except StringBuilderis not thread safe.
Sunrecommends that you use StringBuilderinstead of StringBufferwheneverpossible because StringBuilder will run faster.
QUALITY. PRODUCTIVITY. INNOVATION.
7/25/2019 Basic Programming Session 4
9/17
9
9
Important Methods in the StringBufferand StringBuilder Classes
QUALITY. PRODUCTIVITY. INNOVATION.
This method returns a StringBuffer object and updates the value of the StringBuffer
object that invoked the method call. In both cases, the characters in the StringBufferare reversed, the first character becoming the last, the second becoming the second
to the last, and so on:
public synchronized
StringBuffer
reverse()
This method returns the value of the StringBuffer object that invoked the method call
as a String
public String
toString()
update the value of the object that invoked the method, whether or not the return is
assigned to a variable. This method will take many different arguments, including
boolean, char, double, float, int, long, and others
public synchronized
StringBuffer
append(String s)
This method returns a StringBuilder object and updates the value of the StringBuilder
object that invoke the method call. In both cases, a substring is removed from the
original object.
public StringBuilder
delete(int start, intend)
This method returns a StringBuilder object and updates the value of the StringBuilder
object that invoked the method call. In both cases, the String passed in to the second
argument is inserted into the original StringBuilder starting at the offset location
represented by the first argument (the offset is zero-based).
public StringBuilder
insert(int offset,String s)
7/25/2019 Basic Programming Session 4
10/17
10
10
Java Collections
A collection represents a group of objects
java.util package.
They are basically used to group multiple elements into a single unit. Some collectionsallow duplicate elements while others do not. Some collections are ordered and others arenot.
What can we do with a Collection?
1. Addobjects to the collection.
2. Removeobjects from the collection.
3. Find out if an object(or group of objects) is in the collection
4. Retrievean object from the collection (without removing it).5. Iteratethrough the collection, looking at each element (object) one after another.
QUALITY. PRODUCTIVITY. INNOVATION.
7/25/2019 Basic Programming Session 4
11/17
11
11 QUALITY. PRODUCTIVITY. INNOVATION.
7/25/2019 Basic Programming Session 4
12/17
12
12
Classification
Lists - Listsof things (classes that implement List)
Sets - Uniquethings (classes that implement Set)
Maps - Things with an uniqueID (classes that implement Map)
QUALITY. PRODUCTIVITY.
INNOVATION.
7/25/2019 Basic Programming Session 4
13/17
13
13
Collection Interface concrete implementationclasses
QUALITY. PRODUCTIVITY. INNOVATION.
Class Map Set List Ordered Sorted
HashMap x No No
Hashtable x No No
TreeMap x Sorted By natural order or
custom comparison rules
LinkedHashMap x By insertion orderor last access order
No
HashSet x No No
TreeSet x Sorted By natural order or
custom comparison rules
LinkedHashSet x By insertion order No
ArrayList x By index No
Vector x By index No
LinkedList x By index No
7/25/2019 Basic Programming Session 4
14/17
14
14
ArrayList
ArrayList supports dynamic arrays that cangrow as needed.
In Java, standard arrays are of a fixed length.After arrays are created, they cannot grow orshrink, which means that you must know in
advance how many elements an array will
hold. But, sometimes, you may not know untilrun time precisely how large of an array youneed.
Solution: ArrayLista variable-length arrayof object references. That is, an ArrayList candynamically increase or decrease in size.Array lists are created with an initial size.When this size is exceeded, the collection isautomatically enlarged. When objects areremoved, the array may be shrunk.
A java ArrayList is used to store an ordered
group of elements where duplicatesareallowed.
Most important methods
QUALITY. PRODUCTIVITY. INNOVATION.
add (Object o) - adds an object to the ArrayList
add(int index, Object o)adds the object o the the array list at
the given index
get(int index) - retrieves object reference from ArrayList index
position
size() - returns ArrayList size
remove(int index) - removes element at specified position in the
list. Shifts any subsequent elements to the left
remove (Object o) - removes the object o from the list
set(int index, Object o)- used for updating an element; it
replaces the element present at the specified index with the
object o
int indexOf(Object o)- finds the index in the list of the first
occurrence of the specified element. If the element is not
present in the list returns -1
Object get(int index)returns the object of list which is present
at the specified index
clear() - removes all the elements
boolean contains(Object o)- checks whether the given object o
is present in the array list
7/25/2019 Basic Programming Session 4
15/17
15
15
HashSet
implements the Set interface
doesnt maintain any order, the elements
would be returned in any random order. doesnt allow duplicates. If you try to add a
duplicate element in HashSet, the old valuewould be overwritten.
allows null values however if you insert morethan one nulls it would still return only onenull value.
is non-synchronized
Most important methods
QUALITY. PRODUCTIVITY. INNOVATION.
boolean add(Element e) - adds the element e to the Set
void clear()removes all the elements from the Set
boolean contains(Object o)checks whether the specified
Object o is present in the list or not. If the object has been
found it returns true, false otherwise.
boolean isEmpty()returns true if there is no element in the
Set
int size()- returns the number of elements of a Set
Boolean remove(Object o)removes the specified object from
the Set
7/25/2019 Basic Programming Session 4
16/17
16
16
HashMap
HashMap implementation provides constant-
time performance for the basic operations(get and put), assuming the hash functiondisperses the elements properly among thebuckets.
It is not an ordered collection which means itdoes not return the keys and values in thesame order in which they have been insertedinto the HashMap.
It does not any kind of sorting to the storedkeys and Values
Most important methods
QUALITY. PRODUCTIVITY. INNOVATION.
void clear()- removes all the keys and values form the specified
map
boolean containsKey(Object key)returns true or false based
on whether the specified key is found in the map
boolean containsValue(Object Value)- similar to containsKeymethod, however it looks for the specified value instead of key
Value get(Object key)returns the value of the specified key
boolean isEmpty()checks whether the map is empty
Set keySet()- returns the Set of the keys fetched from the map
value put(Key k, Value v)-inserts key value mapping into the
map.
int size()returns size of the map
Collection values()returns a Collection of values of map
Value remove(Object key)- removes the key-value pair for the
specified key
void putAll(Map m)copies all the elements of a map into the
specified map m
7/25/2019 Basic Programming Session 4
17/17
17
Q & A
QUALITY. PRODUCTIVITY. INNOVATION.