Java program for finding the smallest element in an arraylist

/
0 Comments

 This program also creates an ArrayList called "numbers" and adds some integers to it.

 It then uses a for loop to iterate through the ArrayList, and compares each element to

 the current smallest element. If a smaller element is found, it

 is assigned to the variable "smallest". Finally, the smallest element is printed to the console.


 import java.util.ArrayList;


public class SmallestElementArrayList {

    public static void main(String[] args) {

        ArrayList<Integer> numbers = new ArrayList<>();

        numbers.add(3);

        numbers.add(2);

        numbers.add(5);

        numbers.add(1);

        numbers.add(4);


        int smallest = numbers.get(0);

        for (int i = 1; i < numbers.size(); i++) {

            if (numbers.get(i) < smallest) {

                smallest = numbers.get(i);

            }

        }

        System.out.println("Smallest element in the ArrayList is: " + smallest);

    }

}



You may also like

No comments: