0% found this document useful (0 votes)
11 views6 pages

Java ArrayLists and Arrays Explained

The document provides an overview of Java arrays and ArrayLists, highlighting their differences, creation methods, and how to modify their elements. It explains the concept of two-dimensional arrays, including their declaration, accessing elements, and modification techniques. Additionally, it covers traversal methods for both row-major and column-major orders, as well as the use of enhanced for loops for iterating through 2D arrays.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views6 pages

Java ArrayLists and Arrays Explained

The document provides an overview of Java arrays and ArrayLists, highlighting their differences, creation methods, and how to modify their elements. It explains the concept of two-dimensional arrays, including their declaration, accessing elements, and modification techniques. Additionally, it covers traversal methods for both row-major and column-major orders, as well as the use of enhanced for loops for iterating through 2D arrays.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Firefox about:srcdoc

Cheatsheets / Learn Java

Arrays and ArrayLists

Java ArrayList

In Java, an ArrayList is used to represent a dynamic // import the ArrayList package


list.
import [Link];
While Java arrays are �xed in size (the size cannot be
modi�ed), an ArrayList allows �exibility by being
able to both add and remove elements. // create an ArrayList called students
ArrayList<String> students = new
ArrayList<String>();

Index

An index refers to an element’s position within an array. int[] marks = {50, 55, 60, 70, 80};
The index of an array starts from 0 and goes up to one
less than the total length of the array.
[Link](marks[0]);
// Output: 50

[Link](marks[4]);
// Output: 80

Arrays

In Java, an array is used to store a list of elements of // Create an array of 5 int elements
the same datatype.
int[] marks = {10, 20, 30, 40, 50};
Arrays are �xed in size and their elements are ordered.

1 of 3 7/3/25, 17:52
Firefox about:srcdoc

Array creation in Java

In Java, an array can be created in the following ways: int[] age = {20, 21, 30};
• Using the {} notation, by adding each element
all at once.
• Using the new keyword, and assigning each
int[] marks = new int[3];
position of the array individually. marks[0] = 50;
marks[1] = 70;
marks[2] = 93;

Changing an Element Value

To change an element value, select the element via its int[] nums = {1, 2, 0, 4};
index and use the assignment operator to set a new
// Change value at index 2
value.
nums[2] = 3;

2 of 3 7/3/25, 17:52
Firefox about:srcdoc

Modifying ArrayLists in Java

An ArrayList can easily be modi�ed using built in import [Link];


methods.
To add elements to an ArrayList , you use the
public class Students {
add() method. The element that you want to add
goes inside of the () . public static void main(String[] args)
To remove elements from an ArrayList , you use the {
remove() method. Inside the () you can specify
the index of the element that you want to remove.
// create an ArrayList called
Alternatively, you can specify directly the element that
you want to remove. studentList, which initially holds []
ArrayList<String>
studentList = new ArrayList<String>();

// add students to the ArrayList


[Link]("John");
[Link]("Lily");
[Link]("Samantha");
[Link]("Tony");

// remove John from the ArrayList,


then Lily
[Link](0);
[Link]("Lily");

// studentList now holds [Samantha,


Tony]

[Link](studentList);
}
}

Print Share

3 of 3 7/3/25, 17:52
Firefox about:srcdoc

Cheatsheets / Learn Java

Two-Dimensional Arrays

Nested Iteration Statements

In Java, nested iteration statements are iteration for(int outer = 0; outer < 3; outer++){
statements that appear in the body of another iteration
[Link]("The outer index
statement. When a loop is nested inside another loop,
the inner loop must complete all its iterations before is: " + outer);
the outer loop can continue. for(int inner = 0; inner < 4; inner+
+){
[Link]("\tThe inner
index is: " + inner);
}
}

Declaring 2D Arrays

In Java, 2D arrays are stored as arrays of arrays. int[][] twoDIntArray;


Therefore, the way 2D arrays are declared is similar 1D
String[][] twoDStringArray;
array objects. 2D arrays are declared by de�ning a data
type followed by two sets of square brackets. double[][] twoDDoubleArray;

Accessing 2D Array Elements

In Java, when accessing the element from a 2D array //Given a 2d array called `arr` which
using arr[first][second] , the first index can be
stores `int` values
thought of as the desired row, and the second index
is used for the desired column. Just like 1D arrays, 2D
int[][] arr = {{1,2,3},
arrays are indexed starting at 0 . {4,5,6}};

//We can get the value `4` by using


int retrieved = arr[1][0];

1 of 3 7/3/25, 17:58
Firefox about:srcdoc

Initializer Lists

In Java, initializer lists can be used to quickly give initial // Method one: declaring and
values to 2D arrays. This can be done in two di�erent
intitializing at the same time
ways.
���If the array has not been declared yet, a new double[][] doubleValues = {{1.5, 2.6,
array can be declared and initialized in the same 3.7}, {7.5, 6.4, 5.3}, {9.8, 8.7, 7.6},
step using curly brackets.
{3.6, 5.7, 7.8}};
���If the array has already been declared, the
new keyword along with the data type must
be used in order to use an initializer list // Method two: declaring and initializing
separately:
String[][] stringValues;
stringValues = new String[][]
{{"working", "with"}, {"2D", "arrays"},
{"is", "fun"}};

Modify 2D Array Elements

In Java, elements in a 2D array can be modi�ed in a double[][] doubleValues = {{1.5, 2.6,


similar fashion to modifying elements in a 1D array.
3.7}, {7.5, 6.4, 5.3}, {9.8, 8.7, 7.6},
Setting arr[i][j] equal to a new value will modify the
element in row i column j of the array arr .
{3.6, 5.7, 7.8}};

doubleValues[2][2] = 100.5;
// This will change the value 7.6 to
100.5

Row-Major Order

“Row-major order” refers to an ordering of 2D array for(int i = 0; i < [Link]; i++) {


elements where traversal occurs across each row -
for(int j = 0; j < matrix[i].length;
from the top left corner to the bottom right. In Java,
row major ordering can be implemented by having j++) {
nested loops where the outer loop variable iterates [Link](matrix[i][j]);
through the rows and the inner loop variable iterates
}
through the columns. Note that inside these loops,
when accessing elements, the variable used in the }
outer loop will be used as the �rst index, and the inner
loop variable will be used as the second index.

2 of 3 7/3/25, 17:58
Firefox about:srcdoc

Column-Major Order

“Column-major order” refers to an ordering of 2D array for(int i = 0; i < matrix[0].length; i++)


elements where traversal occurs down each column -
{
from the top left corner to the bottom right. In Java,
column major ordering can be implemented by having for(int j = 0; j < [Link]; j+
nested loops where the outer loop variable iterates +) {
through the columns and the inner loop variable
[Link](matrix[j][i]);
iterates through the rows. Note that inside these loops,
when accessing elements, the variable used in the }
outer loop will be used as the second index, and the }
inner loop variable will be used as the �rst index.

Traversing With Enhanced For Loops

In Java, enhanced for loops can be used to traverse 2D for(String[] rowOfStrings :


arrays. Because enhanced for loops have no index
twoDStringArray) {
variable, they are better used in situations where you
only care about the values of the 2D array - not the for(String s : rowOfStrings) {
location of those values [Link](s);
}
}

Print Share

3 of 3 7/3/25, 17:58

Common questions

Powered by AI

Index-based access in arrays provides quick, direct access to elements via their index, leading to faster retrieval and modification operations than the Iterator or sequential access mechanisms used in ArrayLists, which can impact performance when accessing elements repeatedly in random order. Arrays' predictability in index access offers performance benefits in time-critical applications, although ArrayLists offer superior usability through dynamic resizing and convenient methods for adding or removing elements, essential for varying data sizes and incremental growth usage scenarios .

Row-major order in Java 2D arrays refers to a configuration where traversal proceeds row by row, moving horizontally across each row before advancing to the next one. This approach uses nested loops, where the outer loop iterates over the rows while the inner loop iterates over the columns. In contrast, column-major order traverses down each column first, iterating over the rows in a column before moving to the next column, which involves swapping the roles of the outer and inner loops .

Nesting loops facilitates processing 2D arrays by iteratively accessing each element. Typically, an outer loop traverses the rows of the array, and an inner loop processes each column within a specific row. This enables systematic traversal of every element, simplifying operations like summing, printing, or modifying elements across the array. Such a structure ensures all elements are addressed in an orderly manner, crucial for operations that depend on data order as in row-major or column-major traversal .

A 2D array in Java can be initialized using an initializer list which declares and initializes the array in a single step using curly brackets, or separately with the new keyword specifying the data type and size, followed by assignment using nested braces. This initialization resembles 1D arrays but requires two sets of square brackets and often involves another level of curly braces for each row . This differs from a 1D array, which only requires a single set of curly braces for all elements or can be initialized with the new keyword followed by one set of square brackets .

In Java, 2D arrays are indexed using two indices, the first representing the row and the second the column. This allows for precise access and modification of elements using the syntax arr[row][column]. Care must be taken to ensure the indices remain within bounds to avoid runtime exceptions. Mismanaging indices can lead to logic errors or exceptions, particularly when iterating over the array with loops . This indexing system forms the fundamental basis for operations on 2D arrays, requiring clear understanding when managing complex data structures .

In Java, elements can be removed from an ArrayList using the remove() method. There are two ways to specify what to remove: by providing the index of the element or directly specifying the element itself. If the index is provided, the element at that particular index is removed. If the element is specified, the first occurrence of the element is removed from the list .

When modifying elements in a Java 2D array, it is important to ensure that both row and column indices are within the defined bounds to prevent IndexOutOfBounds exceptions. Consistent data types across elements should be maintained to avoid type mismatches. Additionally, use the correct nesting of loops to properly target specific elements for modification, aligning with intended operations such as total updating or conditional changes based on current values .

Initializer lists allow arrays in Java to be declared and populated with values simultaneously, streamlining array instantiation by removing the need for multiple method calls or assignments. This is particularly beneficial for 2D arrays, where many elements need initialization—making the code more concise and easier to read. It also reduces the likelihood of initialization errors, especially in complex arrays, by visually organizing data into a structured format .

Enhanced for loops in Java are more suitable for operations on 2D arrays when the values themselves are of interest rather than their specific positions. This is because enhanced for loops iterate through each element without providing direct access to their index. They provide a simpler syntax for processing all the values in a 2D array, reducing the risk of errors associated with manual indexing .

The fixed size of arrays in Java means that once they are declared, their size cannot be changed. This restricts their dynamic usability since they cannot accommodate more elements than their initial size. In contrast, ArrayLists are dynamic, allowing addition or removal of elements as needed. This flexibility makes ArrayLists a more versatile choice when the number of elements is not known in advance or expected to change frequently .

You might also like