Java Arrays [g2]
Java Arrays [g2]
ARRAYS
Syntax of Array
Array Operations
various actions that can be
performed on arrays to manipulate
and manage the data they contain.
Passing Array
Methods
manipulate and operate on
collections of data without needing
to return multiple values
Array List
data structure in Java
that works like a
Arrays
One-Dimensional Array
or single dimensional array can be
visualized as a single row or a column of
array elements that are represented by a
variable name and whose elements are
accessed by index values and must deal
with only one parameter.
Multidimensional Array
arranged as an array of arrays. You can look
it as a single container that stores multiple
containers. Each element of a
multidimensional array is an array itself
One-dimensional Arrays
.
Multidimensional Arrays
Array Operations
Sorting Arrays
arranging the elements of
the array in a specific order
Merging arrays
combining two or more arrays
into a single array
Sorting Arrays
Ways:
Arrays.sort()
- built in sorting
Bubble Sort
- manual sorting
Sorting Arrays
Example:
.
Searching Arrays
• List.contains() method
• Stream.anyMatch() method
Searching Arrays using Linear Search method
Syntax:
Searching Arrays using Binary Search method
Searching Arrays using List.contains() method
Syntax:
Searching Arrays using List.contains() method
Searching Arrays using Stream.anyMatch() method
Syntax:
Searching Arrays using Stream.anyMatch() () method
Adding and Removing Elements
Example:
Passing Array to Methods
Modifying elements od
an array in a method
Passing arrays as 02
parameters to method
Returning an array
from a method
Passing arrays to method
Syntax: Example:
Returning an Array from a method
It may be slower than standard arrays, but it is helpful when the size is not
known in advance
Note that creating a large fixed-sized array would cause a waste of space since
ArrayList is part of the collection framework .
.it has better interoperability with other collections. For example, conversion
to a HashSet is straightforward.
Creating an ArrayList
Before using ArrayList, we need to import the java.util.ArrayList package first. Here is how we
can create arraylists in Java:
In the above program, we have used Integer not int. It is because we cannot use primitive
types while creating an arraylist. Instead, we have to use the corresponding wrapper classes.
Here, Integer is the corresponding wrapper class of int.
Creating an ArrayList
1. Add Elements to an ArrayList
To add a single element to the arraylist, we use the add() method of the ArrayList class. For
example,
2. Remove ArrayList Elements
To remove an element from the arraylist, we can use the remove() method of the ArrayList
class. For example,
Converting an ArrayList to an Array
Syntax: