Build a Custom Agent for Agentic Testing.pptxklpathrudu
Empower Your Tech Vision- Why Businesses Prefer to Hire Remote Developers fro...logixshapers59
The 5 Reasons for IT Maintenance - Arna SoftechArna Softech
MiniTool Partition Wizard Free Crack + Full Free Download 2025bashirkhan333g
[Solution] Why Choose the VeryPDF DRM Protector Custom-Built Solution for You...Lingwen1998
Ad
description of Collections, seaching & Sorting
2. The data structures that you choose can make a big difference when
it comes to implementing methods in a natural style, as well as for
performance. Do you need to search quickly through thousands of
sorted items? Do you need to rapidly insert and remove elements
in the middle of an ordered sequence? Do you need to establish
associations between keys and values?
In object-oriented thinking, a data structure, also known as a
container, is an object that stores other objects, referred to as
data or elements. Some people refer to data structures as
container objects
A collection is a container object that represents a group of
objects, often referred to as elements. A collection allows a group of
objects to be treated as a single unit
As is common for modern data structure libraries, the Java
collection library separates interfaces and implementations.
2
3. The Java Collections Framework supports two
types of containers:
One for storing a collection of elements,
simply called a Collection.
The other for storing key/value pairs, called a
Map.
The Java Collections Framework supports
three types of collections
Sets - An instance of Set stores a group of
non-duplicate elements.
Lists - An instance of List stores an ordered
collection of elements.
Queue - An instance of Queue stores objects
that are processed in first-in, first-out fashion
3
4. The collections framework is provided in
java.util package and has three main elements
core interfaces, which allow collections to be
manipulated independent of their implementation
small set of implementation classes, providing data
structures for you to use
an assortment of algorithms, which can be used to
perform various operations on collections, such as
sorting and searching
4
5. add(Object o), addAll(Collection c)
ensures that this collection contains the specified element
remove(Object o), removeAll(Collection c)
removes a single instance of the specified element from
this collection, or all the elements
size()
returns the number of elements in this collection
clear()
removes all of the elements from this collection
toArray()
returns an array containing all of the elements in this
collection
iterator()
returns an iterator over the elements in this collection
5
6. Collection
basic interface that defines all collection operations
Set
extends the Collection interface for sets that maintain
unique elements
List
extends the Collection interface for group of elements in a
sequential order
Map
basic interface for a group of key to value mappings
Additional Interfaces
SortedSet
for sets with elements in sorted order
SortedMap
for maps with keys in sorted order 6
7. Collection Type Description
ArrayList An indexed sequence that grows and shrinks dynamically
LinkedList An ordered sequence that allows efficient insertions and
removal at any location
ArrayDeque A double-ended queue that is implemented as a circular array
HashSet An unordered collection that rejects duplicates
TreeSet A sorted set
EnumSet A set of enumerated type values
LinkedHashSet A set that remembers the order in which elements were
inserted
PriorityQueue A collection that allows efficient removal of the smallest
element
HashMap data structure that stores key/value associations
TreeMap A map in which the keys are sorted
EnumMap A map in which the keys belong to an enumerated type 7
8. implementations will maintain their elements in
sequential order or sequence
can contain duplicates
List interface adds list specific operations
access by numerical position
search in list
operations on parts of a list (called open range-view
operations)
customized iterators
8
9. resizable-array implementation of the List interface
implements all optional list operations, and permits
all elements, including null
in addition to implementing the List interface, this
class provides methods to manipulate the size of the
array that is used internally to store the list
capacity is the size of the array used to store the
elements in the list
as elements are added to ArrayList, its capacity grows
automatically
ensureCapacity() increases the capacity of an
ArrayList instance before adding a large number of
elements
reduces the amount of incremental reallocation
9
12. Vector is similar to ArrayList, but is thread
safe / synchronized
12
element
List
element
…
Thread
1
Thread
2
13. can add elements at end and beginning to a
LinkedList
The Example...
List where each element references previous and
next element in the list
13
14. see ListExample.java
list where each element references previous
and next element in the list
14
Results:
The size is: 6
This
is
is
a
a
test
COMPARE WITH:
list.add("is");
list.add("is");
list.add("a");
list.add("a");
list.addLast("test");
list.addFirst("This");
15. If you need to support random access through an
index without inserting or removing elements from
any place other than the end, ArrayList offers the
most efficient collection.
If, however, your application requires the insertion
or deletion of elements from any place in the list,
you should choose LinkedList.
A list can grow or shrink dynamically. An array is
fixed once it is created. If your application does not
require insertion or deletion of elements, the most
efficient data structure is the array.
15
16. The Stack class represents a last-in first-out stack of objects
The elements are accessed only from the top of the stack
You can retrieve, insert, or remove an element from the top of the
stack
boolean empty() Tests if this stack is empty.
Object peek() Looks at the object at the top of this stack
without removing it from the stack.
Object pop() Removes the object at the top of this stack and
returns that object as the value of this function.
Object push(Object item) Pushes an item onto the top of this
stack.
int search(Object o) Returns the 1-based position where an
object is on this stack.
16
17. interface Map maps keys to values
no duplicate keys
each key maps to only one value
value is retrieved based on a key
the keys order can be sorted (TreeMap), or not
methods:
put(Object key, Object value)
get(Object key)
remove(Object key)
containsKey(Object key)
containsValue(Object value) caution - could be
expensive!
17
18. see HashMapExample.java
18
Results:
The size is: 6
five=cinco
six=seis
two=dos
one=uno
three=tres
four=cuatro
COMPARE WITH:
map.put("one","uno");
map.put("two","deux");
map.put("two","dos");
map.put("three","tres");
map.put("four","cuatro");
map.put("five","cinco");
map.put("six","seis");
19. Hashtable is synchronized, whereas HashMap is
not. This makes HashMap better for non-threaded
applications, as unsynchronized Objects typically
perform better than synchronized ones.
Hashtable does not allow null keys or values.
HashMap allows one null key and any number of
null values.
One of HashMap's subclasses is LinkedHashMap,
so in the event that you'd want predictable iteration
order (which is insertion order by default), you could
easily swap out the HashMap for a LinkedHashMap.
This wouldn't be as easy if you were using
Hashtable. 19
20. java.util.Hashtable
stores data items based on a key derived from
a given formula
unique key returned by hashCode()
use Hashtable class if you will be storing a
large amount of data in memory and then
searching it
20
21. see HashtableExample.java
we stored name value pairs, where:
name = animals
value = color
Java computed it’s own hash number
we retrieved data by entering name ("cow" in
our case)
21
{Dog=white, Fly=black, Hen=red, Ant=black, Cow=orange, Pig=pink,
Cat=blue}
Which animal? Cow
Cow : orange
22. The Collections class contains various static
methods for operating on collections and
maps, for creating synchronized collection
classes, and for creating read-only collection
classes.
22
TestCollections
23. The Arrays class contains various static
methods for sorting and searching arrays, for
comparing arrays, and for filling array elements.
It also contains a method for converting an
array to a list.
23
TestArrays
25. Iterator provides a way to access the elements of
the collection sequentially without exposing its
underlying representation
boolean hasNext()
returns true if the iteration has more elements
Object next()
returns the next element in the iteration
void remove()
removes from the underlying collection the last element
returned by the iterator (optional operation)
25
26. implementations of Set will not allow duplicate
elements
it does not add any new methods to Collection
interface,
but adds the restriction that duplicates are not
allowed
a Set models a mathematical set
26
27. Results:
The size is: 4
a
is
This
test
27
HashSetExample
The HashSet class is a concrete class that implements the
Set interface
It can be used to store duplicate-free elements
uses hashcode() to determine if an object has been added to the
set “SEE NEXT SLIDES ABOUT HASH CODE”
28. 28
Implementing hashcode: if a class overrides equals, it must
override hashCode when they are both overridden, equals
and hashCode must use the same set of fields
if two objects are equal, then their hashCode values must be
equal as well. It is a popular misconception that hashCode
provides a unique identifier for an object. It does not.
hashCode() methodwhich digests the data stored in an instance of
the class into a single hash value (a 32-bit signed integer). This hash
is used by other code when storing or manipulating the instance - the
values are intended to be evenly distributed for varied inputs in order
to avoid clustering. This property is important to the performance of
hashtables and other data structures that store objects in groups
("buckets") based on their computed hash values
29. The semantics of equals() for a given class are left to the
implementer; defining what equals() means for a given class is part
of the design work for that class. The default implementation,
provided by Object, is simply reference equality: Under this default
implementation, two references are equal only if they refer to the
exact same object.
The default implementation of hashCode() provided by Object is
derived by mapping the memory address of the object to an integer
value. Because on some architectures the address space is larger
than the range of values for int, it is possible that two distinct
objects could have the same hashCode(). If you override
hashCode(), you can still use the System.identityHashCode()
method to access this default value.
What would happen if Integer did not override equals() and
hashCode()? Nothing, if we never used an Integer as a key in a
HashMap or other hash-based collection. However, if we were to use
such an Integer object for a key in a HashMap, we would not be able to
reliably retrieve the associated value, unless we used the exact same
Integer instance in the get() call as we did in the put() call. This would
require ensuring that we only use a single instance of the Integer
object corresponding to a particular integer value throughout our
program. Needless to say, this approach would be inconvenient and
error prone.
29
30. Why does our root object class need hashCode(), when its discriminating
ability is entirely subsumed by that of equals()? The hashCode() method
exists purely for efficiency. The Java platform architects anticipated the
importance of hash-based collection classes -- such as Hashtable,
HashMap, and HashSet -- in typical Java applications, and comparing
against many objects with equals() can be computationally expensive.
Having every Java object support hashCode() allows for efficient storage
and retrieval using hash-based collections
The behavior of equals() and hashCode() may even be imposed by the
specification of a superclass or interface. For example, the List interface
requires that a List object is equal to another object if and only if the other
object is also a List and they contain the same elements (Object.equals()
on the elements) in the same order. The requirements for hashCode() are
defined -- the hashCode() value of a list must conform to the following
calculation:
30
hashCode = 1; Iterator i = list.iterator();
while (i.hasNext()) { Object obj = i.next();
hashCode = 31*hashCode + (o
Not only is the hash value dependent on the contents of the list, but the specific
algorithm for combining the hash values of the individual elements is specified as
well.bj==null ? 0 : obj.hashCode()); }
31. Previously, we used Comparator with Arrays, now
lets try it out with collections
Comparators can be used to control the order of
certain data structures (such as TreeSet or
TreeMap).
31
The Comparator interface declares a compare method with two explicit
parameters:
public interface Comparator<T>
{
int compare(T a, T b);
}
Just like the compareTo method, the compare method returns a negative
integer if a comes before b, zero if they are identical, or a positive integer
otherwise
33. When you take an element out of a Collection,
you must cast it to the type of element that is
stored in the collection.
Besides being inconvenient, this is unsafe.
The compiler does not check that your cast is the
same as the collection's type, so the cast can fail at
run time.
33
34. Generics provides a way for you to
communicate the type of a collection to the
compiler, so that it can be checked.
Once the compiler knows the element type of
the collection, the compiler can check that you
have used the collection consistently and can
insert the correct casts on values being taken
out of the collection.
34
35. Here is a simple example taken from the
existing Collections tutorial:
// Removes 4-letter words from c. Elements
must be strings
static void expurgate(Collection c) {
for (Iterator i = c.iterator(); i.hasNext(); )
if (((String) i.next()).length() == 4)
i.remove();
}
35
ex·pur·gate· (eks′pər gāt′)
transitive verb
to remove passages considered obscene or otherwise objectionable from (a book,
etc.) to expunge (objectionable material) from; delete
36. Here is the same example modified to use
generics:
// Removes the 4-letter words from c
static void expurgate(Collection<String> c) {
for (Iterator<String> i = c.iterator();
i.hasNext(); )
if (i.next().length() == 4)
i.remove();
}
36