Skip to content

Commit 7406a40

Browse files
authored
[Edit] Java: .set() (#7097)
* [Edit] Java: .set() * minor content fix ---------
1 parent db5dfa5 commit 7406a40

File tree

1 file changed

+102
-14
lines changed
  • content/java/concepts/array-list/terms/set

1 file changed

+102
-14
lines changed
Lines changed: 102 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,61 +1,149 @@
11
---
22
Title: '.set()'
3-
Description: 'Replaces the element present in a specified position in an ArrayList.'
3+
Description: 'Replaces the element present at a specified position with another element in an ArrayList.'
44
Subjects:
55
- 'Code Foundations'
66
- 'Computer Science'
77
Tags:
88
- 'Arrays'
99
- 'Data Types'
10+
- 'Index'
11+
- 'Methods'
1012
CatalogContent:
1113
- 'learn-java'
1214
- 'paths/computer-science'
1315
---
1416

15-
The **`.set()`** method replaces an element at a specified position with another element in an `ArrayList` instance. After execution, the replaced element is returned.
17+
In Java, the **`.set()`** [method](https://www.codecademy.com/resources/docs/java/methods) replaces the element present at a specified position with another element in an `ArrayList`. After execution, the method returns the replaced element.
18+
19+
Understanding how `.set()` works is crucial when dealing with mutable lists in Java, especially when updating or modifying elements during processing.
1620

1721
## Syntax
1822

1923
```pseudo
20-
arrayListInstance.set(index, newElement);
24+
arrayList.set(index, element);
2125
```
2226

23-
An element at a specified `index` is replaced in an `arrayListInstance` with the `newElement`.
27+
**Parameters:**
28+
29+
- `index`: The position in the list where the element should be replaced.
30+
- `element`: The new element that will replace the old one at the given index.
31+
32+
**Return value:**
2433

25-
> **Note:** The `newElement` must be of the same [data type](https://www.codecademy.com/resources/docs/java/data-types) as the rest of the elements in `arrayListInstance`. Otherwise, an error will occur.
34+
The `.set()` method returns the replaced element.
2635

27-
## Example
36+
> **Note:** The `element` must be of the same [data type](https://www.codecademy.com/resources/docs/java/data-types) as the rest of the elements in the `arrayList`. Otherwise, an [error](https://www.codecademy.com/resources/docs/java/errors) will occur.
2837
29-
In the example below, an empty `ArrayList` instance `studentList` is created and can hold `String`-type elements. Next, a few elements are added with the [`.add()`](https://www.codecademy.com/resources/docs/java/array-list/add) method. Lastly, two students are replaced with the `.set()` method:
38+
## Example 1: Basic Usage of `.set()`
39+
40+
This example uses the `.set()` method to replace elements at multiple positions in an `ArrayList`:
3041

3142
```java
3243
import java.util.ArrayList;
3344

3445
public class Students {
3546
public static void main(String[] args) {
36-
47+
// Create an ArrayList
3748
ArrayList<String> studentList = new ArrayList<String>();
3849

39-
// Add new values to the studentList
50+
// Add values to the ArrayList
4051
studentList.add("John");
4152
studentList.add("Lily");
4253
studentList.add("Samantha");
4354
studentList.add("Tony");
4455

45-
// `.set()` method returns replaced element's value
56+
// Replace elements at multiple positions in the ArrayList
4657
String replacedStudentOne = studentList.set(1, "David");
4758
String replacedStudentTwo = studentList.set(2, "George");
4859

49-
// Output updated ArrayList and replaced elements
60+
// Print the updated ArrayList
5061
System.out.println("Updated ArrayList: " + studentList);
51-
System.out.println("Replaced Elements: " + replacedStudentOne + " and " + replacedStudentTwo);
5262
}
5363
}
5464
```
5565

56-
The output should look like this:
66+
Here is the output:
5767

5868
```shell
5969
Updated ArrayList: [John, David, George, Tony]
60-
Replaced Elements: Lily and Samantha
6170
```
71+
72+
## Example 2: Using `.set()` with Integers
73+
74+
This example uses the `.set()` method to replace an integer with another integer in an `ArrayList`:
75+
76+
```java
77+
import java.util.ArrayList;
78+
79+
public class Example2 {
80+
public static void main(String[] args) {
81+
// Create an ArrayList
82+
ArrayList<Integer> numbers = new ArrayList<>();
83+
84+
// Add values to the ArrayList
85+
numbers.add(10);
86+
numbers.add(20);
87+
numbers.add(30);
88+
89+
// Replace the second element
90+
numbers.set(1, 99);
91+
92+
// Print the updated ArrayList
93+
System.out.println(numbers);
94+
}
95+
}
96+
```
97+
98+
Here is the output:
99+
100+
```shell
101+
[10, 99, 30]
102+
```
103+
104+
## Example 3: Handling Index Errors
105+
106+
This example attempts to replace an element at an out-of-bounds index using the `.set()` method, resulting in an `IndexOutOfBoundsException`:
107+
108+
```java
109+
import java.util.ArrayList;
110+
111+
public class Example3 {
112+
public static void main(String[] args) {
113+
// Create an ArrayList
114+
ArrayList<String> colors = new ArrayList<>();
115+
116+
// Add values to the ArrayList
117+
colors.add("Red");
118+
colors.add("Green");
119+
120+
try {
121+
colors.set(5, "Blue");
122+
} catch (IndexOutOfBoundsException e) {
123+
System.out.println("Error: " + e.getMessage());
124+
}
125+
}
126+
}
127+
```
128+
129+
In this example, the `try...catch` block is used to catch the exception and display the error message.
130+
131+
Here is the output:
132+
133+
```shell
134+
Error: Index 5 out of bounds for length 2
135+
```
136+
137+
## Frequently Asked Questions
138+
139+
### 1. Can `.set()` be used to add new elements to a list?
140+
141+
No. The `.set()` method replaces an existing element at a given index. To insert a new element, use `.add()` instead.
142+
143+
### 2. Is `.set()` available for all collections in Java?
144+
145+
No. `.set()` is only available for classes that implement the `List` interface, such as `ArrayList`, `LinkedList`, and `Vector`.
146+
147+
### 3. Does `.set()` change the size of the list?
148+
149+
No. `.set()` only modifies the value at the specified index.

0 commit comments

Comments
 (0)