UNIT-1
DATA STRUCTURES IN
JAVA
MAPS
A map is a data type that keeps associations
between keys and values.
example: a map that associates names with
colors. This map might describe the favorite
colors of various people.
A map keeps associations between key and
value objects.
Mathematically, a map is a function from one
set, the key set, to another set, the value
set.
Every key in the map has a unique value, but
a value may be associated with several keys.
Just as there are two kinds of set
implementations, the Java library has
two
implementations
for
maps:
HashMap and TreeMap. Both of them
implement the Map interface.
After constructing a HashMap or
TreeMap, you should store the reference
to the map object in a Map reference:
Map<String, Color>
favoriteColors = new HashMap<String,
Color>();
Use the put method to add an
association:
favoriteColors.put("Juliet", Color.PINK);
You can change the value of an existing
association, simply by calling put again:
favoriteColors.put("Juliet", Color.RED);
The get method returns the value
associated with a key.
Color julietsFavoriteColor =
favoriteColors.get("Juliet");
If you ask for a key that isn't associated
with any values, then the get method
returns null.
To remove a key and its associated
value, use the remove method:
favoriteColors.remove("Juliet");
Example : MapDemo.java
SETS
A set is an unordered collection of
distinct elements. Elements can be
added, located, and removed.
Fundamental operations on a set:
Adding an element
Removing an element
Containment testing (does the set contain a given object?)
Listing all elements (in arbitrary order)
Sets don't have duplicates. Adding a
duplicate of an element that is already
present is silently ignored.
we could use a linked list to implement
a set. But adding, removing, and
containment testing would be relatively
slow, because they all have to do a
linear search through the list.
(Adding requires a search through the
list to make sure that we don't add a
duplicate.)
In fact, there are two different data structures
for this purpose, called hash tables and
trees .
The standard Java library provides set
implementations based on both data
structures, called HashSet and TreeSet. Both
of these data structures implement the Set
interface.
Set<String>names=new Hash Set<String>();
Note that we store the reference to the
HashSet<String> object in a Set<String>
variable.
After you construct the collection object, the
implementation no longer matters; only the
interface is important.
Adding and removing set elements is
straightforward:
names.add("Romeo");
names.remove("Juliet");
The contains method tests whether an
element is contained in the set:
if (names.contains("Juliet")) . . .
Finally, to list all elements in the set,
get an iterator. As with list iterators,
you use the next and hasNext methods
to step through the set.
Iterator<String> iter = names.iterator();
while (iter.hasNext())
{
String name = iter.next();
//Do something with name
}
An iterator visits all elements in a set.
A set iterator does not visit the elements
in the order in which you inserted them.
The set implementation rearranges the
elements so that it can locate them
quickly.
You cannot add an element to a set at
an iterator position.
Iterator interface has no previous
method to go backwards through the
elements.
Because the elements are not ordered,
it is not meaningful to distinguish
between going forward and going
backward.
Example : SetDemo.java
GENERICS
Generic programming involves the
design and implementation of data
structures and algorithms that work for
multiple types.
In Java, generic programming can be
achieved with inheritance or with type
variables.
A generic class has one or more type
variables.
The ArrayList class is a generic class : it
has been declared with a type variable
E. The type variable denotes the
element type:
public class ArrayList<E>
{
public ArrayList() {. . .}
public void add(E element) {. . .}
...
}
Here, E is the name of a type variable,
not a Java keyword.
Type variables can be instantiated with class or
interface types.
In order to use a generic class, you need to
instantiate the type parameter, that is, supply an
actual type.
You can supply any class or interface type,
for example :
ArrayList<BankAccount>
ArrayList<Measurable>
However, you cannot substitute any of the eight
primitive types for a type parameter.
It
would
be
an
error
to
declare
an
ArrayList<double> . Use the corresponding
wrapper class instead, such as ArrayList<Double>
Implementing Generic
Types
write a very simple generic class that
stores pairs of objects, each of which can
have an arbitrary type.
For example,
Pair<String, Integer> result = new Pair<String, Integer>("Harry
Morgan", 1729);
The getFirst and getSecond methods retrieve
the first and second values of the pair.
String name = result.getFirst();
Integer number = result.getSecond();
This class can be useful when you implement
a method that computes two values at the
same time.
The generic Pair class requires two
type parameters, one for the type of
the first element and one for the type
of the second element.
We need to choose variables for the
type parameters. It is considered good
form to use short uppercase names for
type variables, such as those in the
following table:
Type
Variable Meaning
E -----Element type in a collection
K -----Key type in a map
V-----Value type in a map
T -----General type
S , U----Additional general types
Type variables of a generic class follow
the class name and are enclosed in
angle brackets.
Use type parameters for the types of
generic
instance
variables, method
parameters, and return values.
Now it is an easy matter to replace all
String types with the type variable S and
all Integer types with the type variable T .
This completes the declaration of the
generic Pair class. It is ready to use whenever you need to form a pair of two
objects of arbitrary types.
The following sample program shows how
to make use of a Pair for returning two
values from a method.
Example program
implemented
in
PairDemo.java
for pair implementation is
the
following
program
Generic Methods
A generic method is a method with a
type parameter.
Such a method can occur in a class
that in itself is not generic. You can
think of it as a template for a set of
methods that differ only by one or
more types.
Supply the type parameters of a
generic method between the modifiers
and the method return type.
When you call the generic method, you
need not specify which type to use for
the type parameter. (In this regard,
generic methods differ from generic
classes.)
Simply
call
the
method
with
appropriate parameters, and the
compiler will match up the type
parameters with the parameter types.
Wrapper classes
To treat primitive type values as objects,
you must use wrapper classes.
Because numbers are not objects in Java,
you cannot directly insert them into array
lists.
For example, you cannot form an
ArrayList<double>.
To store sequences of numbers in an
array list, you must turn them into objects
by using wrapper classes.
There are wrapper classes for all eight
primitive types:
Note that the wrapper class names
start with uppercase letters, and that
two of them differ from the names of
the corresponding primitive type:
Integer and Character.
Each wrapper class object contains a
value of the corresponding primitive
type.
For example, an object of the class
Double contains a value of type double
(see Figure below).
Wrapper objects can be used anywhere
that objects are required instead of
primitive type values.
For example, you can collect a
sequence of floating-point numbers in
an ArrayList<Double>
Conversion between primitive types
and the corresponding wrapper classes
is automatic. This process is called
auto-boxing (even though autowrapping would have been more
consistent).
Concept of Serialization
The process of saving an object, and all
the objects that it references, to a
stream.
Because each object is assigned a serial
number on the stream.
If the same object is saved twice, only
the serial number is written out the
second time. When the objects are read
back in, duplicate serial numbers are
restored as references to the same
object.
Interface java.io.Serializable
A class should implement this interface
in order to enable serialization of
objects.