Monday, April 28, 2025

Java OO Tutorial - ArrayList - For Loop - ForEach

For loops and foreach loops are commonly used with ArrayLists to iterate over the elements of the list and perform various operations.

import java.util.Collections is a statement in Java that allows you to access the methods and classes defined in the java.util.Collections package.

import java.util.ArrayList;
import java.util.Collections;

public class Main {	
	
	public static void main(String[] args) {
		
		ArrayList<String> pLanguages = new ArrayList<String>();
		
		pLanguages.add("Lisp");
		pLanguages.add("Java");
		pLanguages.add("Python");
		pLanguages.add("C++");
		pLanguages.add("Ada");
		
		System.out.println(pLanguages); 
		
		//System.out.println("Number of elements: " + pLanguages.size());
		
		Collections.sort(pLanguages);
		
		for (String x : pLanguages) {
			System.out.println(x);
		}
		
		/*
		for (int x = 0; x < pLanguages.size(); x++) {
			System.out.println("Index: " + x + " " + pLanguages.get(x));
		}
		*/
	}		
}

Here's a detailed explanation of the code block by block: 

import java.util.ArrayList;
import java.util.Collections;

public class Main {	
	
	public static void main(String[] args) {
		
		ArrayList<String> pLanguages = new ArrayList<String>();
		
		pLanguages.add("Lisp");
		pLanguages.add("Java");
		pLanguages.add("Python");
		pLanguages.add("C++");
		pLanguages.add("Ada");
		
		System.out.println(pLanguages); 

In this code, we first import the necessary classes: ArrayList and Collections. We then create an ArrayList of Strings called pLanguages and add five programming languages to it using the add method. We then print the contents of the ArrayList using System.out.println(pLanguages)

		//System.out.println("Number of elements: " + pLanguages.size());

This line is commented out, but it shows how to get the number of elements in the ArrayList using the size method. 

		Collections.sort(pLanguages);

This line sorts the ArrayList in alphabetical order using the sort method of the Collections class. 

		for (String x : pLanguages) {
			System.out.println(x);
		}

This block of code uses a foreach loop to iterate over each element of the ArrayList and print it to the console. The loop variable x is of type String and takes on the value of each element of the ArrayList in turn. 

		/*
		for (int x = 0; x < pLanguages.size(); x++) {
			System.out.println("Index: " + x + " " + pLanguages.get(x));
		}
		*/

This block of code is commented out, but it shows how to use a traditional for loop to iterate over the ArrayList and print each element along with its index. The loop variable x is of type int and takes on the values of the indices of the ArrayList elements. The get method is used to retrieve the element at each index.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...