4. Write a Java program to test if the first and the last
element of an array list of integers are same
5. Write a Java program to test if the first and the last element
of two array list of integers are same
// Java code to find first and last element
// of ArrayList
import java.util.ArrayList;
public class Main{
// main method
public static void main(String[] args)
{
// creating an Empty Integer ArrayList
ArrayList<Integer> list = new ArrayList<Integer>(5);
// using add() to initialize values
list.add(1);
list.add(2);
list.add(3);
list.add(4);
// printing initial value ArrayList
System.out.println("ArrayList1: " + list);
// find first element
int first = list.get(0);
// find last element
int last = list.get(list.size() - 1);
if(first==last)
System.out.println("first element and last element are equal");
else
System.out.println("first element and last element are not equal");
ArrayList<Integer> list1 = new ArrayList<Integer>(5);
// using add() to initialize values
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);
System.out.println("ArrayList2: " + list);
// find first element
int first1 = list.get(0);
// find last element
int last1 = list.get(list.size() - 1);
// print first and last element of ArrayList
if(first==last && first1==last1)
System.out.println("first element and last element are equal in both lists");
else
System.out.println("first element and last element are not equal in both lists");
}
}
Output:
Get Answers For Free
Most questions answered within 1 hours.