- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to Iterate over an ArrayList
In this article, we will understand how to iterate over an ArrayList. The ArrayList class is a resizable array, which can be found in the java. util package. The difference between a built-in array and an ArrayList in Java, is that the size of an array cannot be modified.
Below is a demonstration of the same −
Suppose our input is −
Run the program
The desired output would be −
A elements of the list are: 50 100 150 200 250 300 350
Algorithm
Step 1 - START Step 2 - Declare namely Step 3 - Define the values. Step 4 - Create a list of integers and initialize elements in it. Step 5 - Display the list on the console. Step 6 - Iterate over the elements, and fetch each element using ‘get’ method. Step 7 - Display this on the console. Step 6 - Stop
Example 1
Here, we bind all the operations together under the ‘main’ function.
import java.util.*; public class Demo { public static void main(String[] args){ System.out.println("The required packages have been imported"); List<Integer> numbers = Arrays.asList(50, 100, 150, 200, 250, 300, 350); System.out.println("A list is declared"); System.out.println("\nA elements of the list are: "); for (int i = 0; i < numbers.size(); i++) System.out.print(numbers.get(i) + " "); } }
Output
The required packages have been imported A list is declared A elements of the list are: 50 100 150 200 250 300 350
Example 2
Here, we encapsulate the operations into functions exhibiting object oriented programming.
import java.util.*; public class Demo { static void multiply(List<Integer> numbers){ System.out.println("\nA elements of the list are: "); for (int i = 0; i < numbers.size(); i++) System.out.print(numbers.get(i) + " "); } public static void main(String[] args){ System.out.println("The required packages have been imported"); List<Integer> input_list = Arrays.asList(50, 100, 150, 200, 250, 300, 350); System.out.println("A list is declared"); multiply(input_list); } }
Output
The required packages have been imported A list is declared A elements of the list are: 50 100 150 200 250 300 350
Advertisements