A better way to
add and delete elements in arrays
- Dynamic
arrays
(a.k.a.
ArrayList in
Java) consists of:
- A (fixed size)
array
- A count of
the actual number of
elements stored in
the array:
Schematically:
Currently,
there are
2 values stored
in the array
|
|
A better way to
add and delete elements in arrays
- Dynamic
arrays
(a.k.a.
ArrayList in
Java) consists of:
- Inserting
a new value
will increase the
count
- If the
array is
not full,
we do not need to
increase its
size
Schematically:
add(8)
will result in:
Now there are
3 values stored in the
array
|
- The
array is
increased
only when
the add( ) operation
encounters a
full array
- The
array is
reduced when
the
occupancy drops
below a
certain threshold
|
A better way to
add and delete elements in arrays
The array doubling algorithm
The array doubling algorithm
The array doubling algorithm
The array doubling algorithm
The
array reduction
algorithm is
similar --
we will discuss
more about
array reduction
later
(Stack)
Example creating an
ArrayList object
Some
commonly used methods in the
ArrayList class
Inserting and
removing
elements
in an ArrayList
- add(E e):
-
appends
the element e
to end of the
ArrayList
[E is the
declared data type
of the ArrayList elements]
E.g.:
numbers.add(99);
|
- add(int index, E elem):
- remove(int index):
|
Retrieving and
updating elements
in an ArrayList
- get(int index):
- set(int index, E elem):
-
Note:
- If the element at the
index
does not exist,
get( ) and
set( ) will
throw
IndexOutOfBoundsException.
|
|
DEMO:
08-arraylist/01-arraylist/Demo.java
Iterating through an
ArrayList
DEMO:
demo/08-arraylist/01-arraylist/Demo2.java
Java's
Iterator interface
and
Iterable interface
-
Iterator is
an interface
(class containing all
virtual methods) in
java.util.Iterator
- An object that
implements the
Iterator interface
must provide
at least the
following methods:
hasNext(): returns true if the iteration has more elements
next(): return the next element in the iteratinr
|
- An Iterator allows
the user to
iterate over
the elements stored in
a Iterable interface
- An object is
Iterable if
implements the
java.util.Iterable
interface
- It must
implement the
iterator() method
that returns an
Iterator object
|
|
You will see an
example of
iterator implementation when we
discuss
linked lists
Arrays vs ArrayList
- Arrays:
- Pros:
- Uses less memory
- Can store primitive types
- Can be multi-dimensional
|
- Cons:
- Size
cannot change
- Hard to
add/remove elements
|
|
|
Arrays vs ArrayList
- ArrayLists:
- Cons:
- Uses more memory
- Can not
store primitive types
- Can only
be one-dimensional
|
- Pros:
- Size
is dynamic
- Easy to
add/remove elements
|
|
|
❮
❯