Arrays and ArrayList in Java
In this section, we will focus on two important concepts: arrays and ArrayLists.
Arrays are fixed-size collections that allow you to store and access multiple values using a single variable. They are useful when dealing with collections of elements of the same type.
ArrayLists, on the other hand, are dynamic collections that can grow or shrink as needed. They provide flexible storage and manipulation of elements.
By understanding arrays and ArrayLists, you will gain valuable tools for organizing and managing data in your Java programs.
Array
At its core, an array is a data structure that houses a fixed-size sequential collection of elements of uniform type. The array's strength lies in its ability to access elements through indices, providing seamless retrieval, modification, and iteration capabilities.
Arrays emerge as indispensable data structures, offering a systematic approach to store and manipulate collections of elements sharing a common data type. They embody an efficient means of handling multiple values under a single variable, fostering a streamlined coding paradigm.
Declaring an array entails specifying the data type, followed by the array name and square brackets indicating the size or dimension.
Direct hit Program: Store 5 Roll Numbers
Arrays leverage contiguous memory locations for storing elements, ensuring swift and efficient access. A fundamental comprehension of their internal workings is crucial for optimizing code and managing memory effectively.
The internal working of an array involves the way it is stored in memory and how elements are accessed using indices. Here's an overview of the internal workings of a basic, one-dimensional array:
Memory Allocation:
When you declare an array, the programming language allocates a contiguous block of memory to store all its elements. The size of this block is determined by the number of elements in the array multiplied by the size of each element.
Indexing:
The elements in an array are accessed using indices. The index serves as an offset from the starting memory address of the array.
The formula for accessing the memory location of an element is often as follows:
memory_location = base_address + (index * element_size)
.For example, if the base address of an array is 1000, and each element is 4 bytes in size, accessing the element at index 2 would involve calculating
1000 + (2 * 4) = 1008
.
Contiguous Memory:
Because the elements are stored sequentially in memory, moving from one element to the next involves incrementing the memory address by the size of each element.
This contiguous nature allows for efficient access to elements and supports operations like iteration.
Fixed Size:
The size of the array is fixed at the time of declaration. This fixed size is known to the compiler, and it reserves the necessary amount of memory accordingly.
Zero-Based Indexing:
In many programming languages, array indices start from 0. This means that the first element of the array is at index 0, the second at index 1, and so on.
Initialization:
When you initialize an array by assigning values to its elements, the programming language takes care of placing those values in the respective memory locations.
Dynamic Memory Allocation (in some cases):
In certain programming languages, arrays can be dynamically allocated at runtime using constructs like
malloc
( in C) ornew
(in C++). In such cases, the memory for the array is allocated on the heap, and the array size can be determined dynamically.
Understanding the internal workings of arrays is essential for writing efficient and optimized code. It allows programmers to make informed decisions about data access, manipulation, and memory usage.
In Java, arrays are static, implying a fixed size upon declaration. To infuse dynamic behavior, alternative data structures like ArrayLists can be considered.
Arrays are widely used due to their efficiency and simplicity. They find applications in various algorithms such as sorting and searching, and they play a key role in data compression techniques.
It's important to note that while arrays offer fast access to elements, their size is fixed upon declaration, and they may not be the most suitable choice if dynamic resizing is required. Other data structures like linked lists or dynamic arrays may be preferred in such cases.
Array elements are stored in contiguous memory locations. This allows for efficient memory access and retrieval based on the index. The contiguous nature of arrays makes it possible to perform arithmetic on indices to access elements directly.
Array indexing initiates at 0, representing the first element, and spans up to length - 1
.
Arrays transcend primitive types and can store objects, such as strings. for example:
In Java, null
signifies the absence of a value or the default value for object references.
Upon array initialization without explicit population, elements default to null
.
Arrays can be populated through user input or predefined values.
The for-each loop simplifies array iteration, enhancing code readability.
The toString()
method furnishes a string representation of an array, aiding in debugging and logging.
Arrays transcend primitive types and can store objects, enabling the creation of intricate data structures.
Objects within an array find residence in heap memory, with array variables holding references to these objects.
Arrays can be passed as parameters to methods, fostering code modularity and reusability.
example:
In Java, arrays are a fundamental part of the language, and there are several built-in methods to manipulate and work with arrays. Here are some commonly used array methods in Java:
length
property:Returns the number of elements in the array.
clone
method:Creates a shallow copy of the array.
toString
method:Converts the array to a string representation.
sort
method:Sorts the array in ascending order.
binarySearch
method:Searches for a specified value using a binary search algorithm (requires the array to be sorted).
fill
method:Fills the array with a specified value.
copyOf
method:Copies the specified range of the array into a new array.
These are just a few examples of array methods in Java. There are more methods available in the Arrays
class for various array operations. You can explore the Java documentation for java.util.Arrays
for a comprehensive list and details.
Arraylist
An ArrayList
is a data structure in programming that is part of the Java programming language and some other languages. It is a dynamic array implementation, meaning it can dynamically resize itself to accommodate a varying number of elements.
Syntax
The syntax involves creating an
ArrayList
object with a specified type, for example:
ArrayList Methods
add(element)
: Adds an element to the end of the ArrayList.contains(element)
: Checks if the ArrayList contains a specific element.set(index, element)
: Sets the element at a specified index.remove(index)
: Removes the element at a specified index.
Input
Utilize a
Scanner
object to take user input for populating an ArrayList, for example:
Output using basic print method
Simply print the ArrayList using
System.out.println()
. This prints the elements in the ArrayList.
Output using get() method
Iterate through the ArrayList using a loop and print each element using the
get(index)
method, for example:
Index of an ArrayList
Retrieve the element at a specific index using the
get(index)
method, for example:
How is ArrayList capable of storing more than their size?
Internally, ArrayList has a fixed size. When it reaches its capacity and needs more space:
It creates a new ArrayList with double the size.
Copies the old elements to the new ArrayList.
The old ArrayList is deleted.
This process ensures that ArrayLists can dynamically resize and handle more elements than their initial capacity.
Arraylist example
ArrayList Insertion and Shifting Behavior
In Java, the ArrayList
class dynamically resizes and shifts elements when inserting at specific positions:
Insertion at Specified Index:
When you use
add(int index, E element)
on anArrayList
, it inserts the specified element at the specified index.Elements at and to the right of the specified index are shifted to the right.
Dynamic Resizing:
If the internal array is full,
ArrayList
dynamically increases its capacity.Existing elements are copied to the new, larger array.
The new element is then inserted at the specified index in the resized array.
Example:
In this example, when list.add(1, 30)
is called, the ArrayList
shifts the element 20 to the right to make room for the new element 30 at index 1.
Behavior Summary:
Insertion: Inserts the specified element at the specified index.
Shifting: Shifts existing elements to the right starting from the specified index.
Advantages:
Dynamic Sizing:
ArrayList
automatically adjusts its size, making it suitable for scenarios with varying numbers of elements.Efficient Insertions: Efficient for frequent insertions and removals compared to arrays.
Considerations:
Performance: While efficient for most use-cases, inserting elements in the middle of large lists may have performance implications due to the shifting of elements.
Understanding this behavior is crucial for effectively utilizing ArrayList in scenarios where elements need to be inserted at specific positions. This shifting and inserting technique is quite useful for efficiently inserting data at a specific position.
Multidimensional Arrays
Arrays can extend into multiple dimensions, giving rise to matrices or tables of values.
A 2D array essentially comprises an array of arrays, with each sub-array representing a row.
Populating a 2D array involves nested loops for row and column indices.
Iterating over a 2D array and printing its elements employs nested loops.
Dynamic Arrays
For dynamic resizing, consider the use of ArrayLists or other dynamic data structures.
Programs
🎯 Program: Swapping Values in an Array
🎯 Program: Maximum Value of an Array
🎯 Program: Reversing an Array
🎯 Program: Column no not fixed of an 2d array
This comprehensive document serves as a robust reference for Java methods, covering arrays, multidimensional arrays, and associated functions. Gaining proficiency in these concepts is imperative for crafting efficient and organized Java code.
Last updated