Title: 6.0 Fundamental classes
16.0 Fundamental classes collections Overview
- Introduction
- The Java language package is the heart of the
Java language. Many of the classes in the
language package are indispensable when you are
writing Java programs. The language package
contains many classes, each with a variety of
member variables, member constants, and methods. - Program design often requires handling a group
of objects together as a unit. Many a times there
is need to handle a list of objects or to
maintain a mapping of objects. These needs are
satisfied by the Java collections framework. It
provides the programmer with ready to use classes
of lists, sets and maps. - The collections framework also provides a set
of utility methods and interfaces to customize
the existing collection classes.
26.0 Fundamental classes of java.lang package
Overview
- Objective
- After completing this Topic, you will be able
to, write code using fundamental classes of
java.lang package and collection
classes/interfaces. - Java.lang Package
- Object Class
- Wrapper Classes
- Math Class
- String Class
- StringBuffer Class
- Core collection interfaces and classes.
- Hierarchy (Collection and Map)
- Comparator and Comparable Interface
- Pros and Cons of individual collection classes
3java.lang Package
- Most widely used package
- Automatically imported into all programs
- The package contains
- Object class
- Wrapper classes i.e. Boolean, Character, Integer,
etc. - Classes essential for interacting with JVM i.e.
Runtime - For security i.e. SecurityManager
- For loading classes i.e. ClassLoader
- For dealing with Threads i.e. Thread
- For exceptions i.e. Throwable
- Classes that provide standard input, output and
error streams i.e. System - String handling i.e. String and StringBuffer
- Mathematical Functions i.e. Math
4java.lang Package
5Object class
- Superclass of all java classes
- No need to extend explicitly
- All objects including arrays implement the
methods
6Object class
- equals() method
- Return true if two references compared denote the
same object - Should be overridden otherwise perform
comparison - Necessary for method hashCode() to be overridden
when this is overridden - Implements equivalence relation
- Reflexive
- Symmetric
- Transitive
- Consistent
- Should return false for non-null reference value
- hashCode() method
- Used to get hash value for an object
- Value guaranteed to be consistent
- Used for benefit of hashtables of util package.
7Object class
- import java.lang.
- public class equalsDemo
- public static void main(String args) throws
Exception - String snew String("CTS")
- // using getClass() method to get the class
of String object - Object firsts.getClass()
- Object seconds.getClass()
-
- //using equals() method to compare two objects
- if(first.equals(second))
- System.out.println("they are same")
- else
- System.out.println("they are not same")
-
-
- Outputthey are same
8Wrapper Classes
- To manipulate primitive values in java as objects
- All wrapper classes are final
- Objects of wrapper classes that can be
instantiated are immutable - Wrapper Classes
- Byte
- Short
- Integer
- Long
- Float
- Double
- Character
- Boolean
9Wrapper Classes
- Common Wrapper class constructors
- All have two public one-argument constructors
except Character - Taking primitive values, the only one for
Character - WrapperType( type v )
- E.g.
- Character charObj new Character(A)
- Integer intObj new Integer(2345)
- Taking Strings
- WrapperType( String str )
- Throw an unchecked NumberFormatException in case
of numeric types e.g. - Long longObj1 new Long(5.67)
- E.g.
- Boolean boolObj new Boolean(True)
- Long longObj new Long(3445)
-
10Wrapper Classes
- Common wrapper class utility Methods
- Strings to Wrapper Objects
- static WrapperType valueOf( String s )
- e.g
- Integer intObj Integer.valueOf(2004)
- Boolean boolObj Boolean.valueOf(false)
- static WrapperType valueOf( String s, int base )
- e.g.
- Short shortObj Short.valueOf(120,8)
- Character does not define this method
- Numeric wrapper types throw NumberFormatException
- Strings to Wrapper Objects
- String toString()
- e.g.
- String charStr charObj.toString()
- Each wrapper class overrides it from the Object
class
11Wrapper Classes
- Common wrapper class utility Methods (continued)
- Primitive values to Strings
- static String toString( type v )
- e.g.
- String intStr intObj.toString(12)
- Wrapper objects to primitive values
- type typeValue()
- e.g.
- boolean b boolObj.booleanValue()
- Wrapper Comparison, Equality and hashcode
- int compareTo(WrapperType obj2)
- int compareTo(Object obj2)
- boolean equals(Object obj2)
- int hashCode()
12Wrapper Classes
- Numeric Wrapper Classes
- All subclasses of abstract class Number
- Constants defined for every primitive data type
- ltWrapper class namegt.MIN_VALUE
- ltWrapper class namegt.MAX_VALUE
- Any numeric wrapper object can be converted to
any numeric primitive type using typeValue()
method - Converting Strings to Numeric values
- type parseType( String s )
- type parseType( String s, int base )
- Converting Integer values to Strings in different
notations - static String toBinaryString( int i )
- static String toHexString( int i )
- static String toOctalString( int i )
13Wrapper Classes
- Character Class
- Constants
- Character.MIN_VALUE
- Character.MAX_VALUE
- Methods
- static int getNumericValue(char ch)
- static char toUpperCase(char ch)
- static char toLowerCase(char ch)
- static boolean isDigit(char ch)
- Boolean Class
- Wrapper objects
- Boolean.TRUE
- Boolean.FALSE
14Math Class
- Supports Mathematical functions
- Is a final class
- Contains static methods
- Constants
- Math.E
- Math.PI
- Functions
- Exponential Functions
- static double pow(double d1, double d2) d1d2
- static double exp(double d) ed
- static double log(double d) loged
- static double sqrt(double d) d0.5
- Exponential Functions
- static double random() returns number gt 0.0
and lt1.0
15Math Class
- Functions (contd)
- Miscellaneous rounding functions
- Overloaded static abs( type v ) method for int,
long, float and double - Overloaded static min(type v1, type v2) method
for int, long, float and double, where v1 and v2
are of the same type - Overloaded static max(type v1, type v2) method
for int, long, float and double, where v1 and v2
are of same type - static double ceil(double d)
- static double floor(double d)
- static int round(float f)
- static long round(double d)
- Trigonometry functions
- static double sin(double d)
- static double cos(double d)
- static double tan(double d)
- static double toRadians(double degrees)
- static double toDegrees(double radians)
16String Class
- Implements immutable character strings
- Is a final class
- Is thread safe
- Creating and initializing strings
- Directly by literals
- e.g. String str Hello
- Using constructors
- String(String s)
- String()
- e.g. String str new String(New String!!)
- Methods
- To read characters from a string like charAt()
- To compare strings like equals()
- For character case in a string like toUpperCase()
- For concatenation of strings like concat()
- For searching characters and substrings like
indexOf() - Extracting substrings like subString()
- For converting primitive values and objects to
strings like toString()
17StringBuffer Class
- Implements mutable character strings
- Is a final class
- Is thread safe
- Preferred when heavy modification to character
strings is involved - Cannot be stored or cast to String and vice versa
- Constructors
- StringBuffer(String s)
- StringBuffer(int length)
- StringBuffer()
- Other functionalities
- Reading and changing characters using
setCharAt(), charAt() - Constructing Strings using toString()
- Appending, inserting and deleting characters
- Controlling StringBuffer Capacity using
ensureCapacity()
18String StringBuffer Classes
- import java.lang.
- public class StringDemo
- public static void main(String args)
- String strObj "This is a demo String"
- StringBuffer strbufObj new StringBuffer()
- System.out.println("string value " strObj)
- System.out.println("Length "
strObj.length()) - System.out.println("The index of the character
d " strObj.indexOf('d')) - System.out.println("The character at position
10 " strObj.charAt(10)) - System.out.println("The substring from
positions 4 to 10 " strObj.substring(4,10)) - System.out.println("The string in upper case "
strObj.toUpperCase()) - strbufObj strbufObj.append("B").append("e").ap
pend("n") - System.out.println("StringBuffer object "
strbufObj) -
19String StringBuffer Classes
- Output
- string value This is a demo String
- Length 21
- The index of the character d 10
- The character at position 10 d
- The substring from positions 4 to 10 is a
- The string in upper case THIS IS A DEMO STRING
- StringBuffer object Ben
20Core Collections Interfaces and classes
Java.util package
- Collections Framework
- A collection is an object that contains other
objects and provides methods for working on the
objects it contains. - The framework presents a set of standard utility
classes for managing the collections. - Framework parts
- Core Interfaces
- allow collections to be manipulated independently
of their implementation. - Implementation classes
- specific implementations of the core interfaces.
- Utility methods
- used to perform various operations on
collections.
21Hierarchy- Collections and Maps
- Relationship among the core interfaces and the
implementation classes
Collection
Set
List
SortedSet
Vector
Array
LinkedList
HashSet
TreeSet
LinkedHashSet
22Collections
- The Collection interface specifies the contract
that all collections should implement. - Basic Operations
- int size()
- boolean isEmpty()
- boolean contains(Object element)
- boolean add(Object element)
- boolean remove(Object element)
- Bulk operations
- boolean containsAll(Collection c)
- boolean addAll(Collection c)
- boolean removeAll(Collection c)
- boolean retainAll(Collection c)
- void clear()
- Collection provides an iterator that allows
sequential access to its elements. - Iterator iterator()
- boolean hasNext()
- Object next()
- Object remove()
23Collections
- import java.util.
- public class IteratorDemo
- public static void main(String args)
- Collection charList new ArrayList()
- char elements 'a', 'b', 'z', 'p'
- for(int i 0 i lt elements.length i)
- charList.add(new Character(elementsi))
-
- Iterator iter charList.iterator()
- while(iter.hasNext())
- Character ch (Character)iter.next()
- char value ch.charValue()
- System.out.println(value ", ")
-
-
24Hierarchy- Collections and Maps
- Relationship among the core interfaces and the
implementation classes
Maps
SortedMap
TreeMap
HashMap
Hashtable
LinkedHashMap
25Map
- Map defines mapping from keys to values.
- Map entry - ltkey-valuegt pair.
- Keys are unique and there is a many-to-one
mapping between keys and values. - Basic Operations
- Object put(Object key, Object value)
- Object get(Object key)
- Object remove(Object key)
- boolean containsKey(Object key)
- boolean containsValue(Object value)
- int size()
- boolean isEmpty()
- Bulk operations
- void putAll(Map m) //optional
- void clear() //optional
26Map Collection Views
- Provides a collection view of a Map through
following methods - Set keySet() Returns a set view of keys.
- Collection values() Returns a collection view
of values. - Set entrySet() Returns a set view of ltkey,
valuegt entries. - Each ltkey, valuegt pair in the entry set view is
represented by an object implementing Map.Entry
Interface - interface Entry
- Object getKey()
- Object getValue()
- Object setValue(Object value)
27Collections and Maps Properties
28Comparator and Comparable Interface
- Interfaces to sort elements in specific order.
- Comparator Interface
- Total ordering of Objects is governed by a
comparator object that implements the Comparator
interface. - Provides int compare (Object o1, Object o2)
- Comparable Interface
- Used to define the natural order of the objects.
- Provides int compareTo(Object o)
29Pros and Cons of individual collection classes
- List Interface
- ArrayList
- It gives you fast iteration and fast random
access. - Good when fast iteration is needed.
- Not good when we need to do a lot of insertions
and deletions. - Vector
- Provides random access
- Vector() methods are synchronized and thus used
for thread safety. - Synchronized methods add a performance hit.
- LinkedList
- Iterate more slowly than an ArrayList,
- Good when fast insertion and deletion is needed.
30Pros and Cons of individual collection classes
- Set Interface
- HashSet
- Is an unsorted, unordered Set.
- Good when the need is for a collection with no
duplicates and their order for iteration does not
matter. - LinkedHashSet
- Lets you iterate through the elements in the
order in which they were inserted. - Use this class instead of HashSet when the
iteration order is important. - TreeSet
- Is a sorted collection.
- Guarantees that the elements will be in ascending
order, according to the natural order of the
elements . - Lets you specify your own rules for what the
natural order should be.
31Pros and Cons of individual collection classes
- Map Interface
- HashMap
- Is an unsorted, unordered Map.
- HashMap allows one null key in a collection and
multiple null values in a collection. - Hashtable
- Hashtable is synchronized counterpart of HashMap.
- A Hashtable doesnt let you have anything thats
null. - LinkedHashMap
- Maintains insertion order (or, optionally, access
order). - TreeMap
- TreeMap is a sorted Map.
32Fundamental Classes Collections Summary
- Java.lang package is by default imported by every
java source code and is the mother of all
classes. - Object class is the super class of all java
classes and contains many basic methods that are
implemented by all other classes. - The wrapper classes are he final classes that
manipulate the primitive values in java as
objects. - Math class is another final class that supports
mathematical functions - String and StringBuffer are other two final
classes that allow to work with character
strings. - A collection is an object that contains other
objects and provides methods for working on the
objects it contains. - A collection can consist of the same types of
objects,and it can also contain objects of
different types.
33Fundamental Classes Collections Summary
- The collections framework is provided in the
java.util package. - Collections is a class, with static utility
methods, while Collection is an interface with
declarations of the methods common to most
collections including add, remove, contains,
size, and iterator. - The core interfaces are Collection, List, Set,
Map, SortedSet, SoretMap. - The implementation classes are ArrayList,
Vector, LinkedList, HashSet, LinkedHashSet,
TreeSet, HashMap, LinkedHashMap, Hashtable,
TreeMap. - Collection provides an iterator that allows
sequential access to its elements. - Classes that provide sorted collections TreeSet
and TreeMap - Classes that provide random access ArayList and
Vectors