Java .set()

StevenSwiniarski's avatar
Published Jun 30, 2022
Contribute to Docs

The .set() method replaces the current entry in the underlying collection of a ListIterator object. This is the last item returned by the .next() or .previous() methods.

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours

Syntax

myListIterator.set(value);

Where myListIterator is a ListIterator object, and value is the object to use in replacing the current element in the underlying collection.

Example

This example populates an ArrayList and then replaces the existing values in the collection:

import java.util.*;
public class Example {
public static void main(String args[]) {
// Create a new ArrayList
ArrayList l = new ArrayList();
// Add some items to the ArrayList
l.add(1);
l.add(2);
l.add(3);
l.add(4);
l.add(5);
System.out.println(l);
ListIterator i = l.listIterator();
// Loop through ArrayList contents
while(i.hasNext()) {
int item = (Integer) i.next();
i.set(item * 2);
}
System.out.println(l);
}
}

This results in the following output:

[1, 2, 3, 4, 5]
[2, 4, 6, 8, 10]

All contributors

Contribute to Docs

Learn Java on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours