ArrayList Lecture - Google Docs (1)
ArrayList Lecture - Google Docs (1)
ArrayList Lecture - Google Docs (1)
● W
hat is an ArrayList?
java.util
AnArrayListis a part of Java'sCollection Framework,located in the
package.
It is adynamic arraythat can grow and shrink asneeded. Unlike arrays, its size is not
fixed.
D
○ ynamic resizing.
○ Easy to add, remove, and manipulate elements.
○ Built-in methods for common tasks.
Declaration:
add()
1. Adding Elements:
Example:
Example:
set()
3. Updating Elements:
Example:
c ities.set(1, "Tokyo");
System.out.println(cities); // Output: [New York, Tokyo]
remove()
4. Removing Elements:
Example:
ities.remove("Tokyo");
c
System.out.println(cities); // Output: [New York]
size()
5. Checking Size:
Example:
System.out.println(cities.size()); // Output: 1
isEmpty()
6. Checking if Empty:
Example:
clear()
7. Clearing the List:
Example:
c ities.clear();
System.out.println(cities); // Output: []
contains()
8. Checking for an Element:
Example:
sing a
U forloop:
for (int i = 0; i < cities.size(); i++) {
System.out.println(cities.get(i));
}
sing an enhanced
U forloop:
for (String city : cities) {
System.out.println(city);
}
1. Compare Two ArrayLists
Example:
import java.util.ArrayList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
Example:
import java.util.ArrayList;
Collections.max()and
You can use the Collections.min()methods to find the largest
ArrayList
and smallest elements in an .
Example:
import java.util.ArrayList;
import java.util.Collections;
Example:
import java.util.ArrayList;
P
● roblem: Manage the marks of students in a class using an ArrayList.
● Operations:
1. Add marks of students.
2. Display all marks.
3. Update a specific student's mark.
4. Remove a mark based on index.
5. Calculate the average of all marks.
Code Example:
import java.util.ArrayList;
.
1 dd scores of participants to the list.
A
2. Sort the scores in descending order.
3. Find the highest and lowest scores in the competition.
4. Compare the scores list with another list of predefined scores to check if they match.
[85, 92,
Inputs to Provide:Participants' scores: 78, 90, 88]
[92, 85, 78, 90,
Predefined scores for comparison: 88]
Expected Output: