Below Java program that checks if an ArrayList of characters represents a palindrome:
import java.util.ArrayList;import java.util.List;public class PalindromeCheck {public static void main(String[] args) { List<Character> characters1 = new ArrayList<>(); characters1.add('r'); characters1.add('a'); characters1.add('c'); characters1.add('e'); characters1.add('c'); characters1.add('a'); characters1.add('r'); List<Character> characters2 = new ArrayList<>(); characters2.add('h'); characters2.add('e'); characters2.add('l'); characters2.add('l'); characters2.add('o'); System.out.println("List 1 is a palindrome: " + isPalindrome(characters1)); System.out.println("List 2 is a palindrome: " + isPalindrome(characters2)); } public static boolean isPalindrome(List<Character> characters) { int left = 0;
int right = characters.size() - 1; while (left < right) {if (characters.get(left) != characters.get(right)) { return false; } left++; right--; }return true; }
}
Explanation:
- We define a class called PalindromeCheck.
- In the main method, we create two ArrayLists of characters - characters1 and characters2. characters1 represents a palindrome (racecar), and characters2 is not a palindrome (hello).
- We call the isPalindrome method to check whether each ArrayList represents a palindrome or not.
- The isPalindrome method takes an ArrayList of characters as input and returns a boolean value indicating whether it is a palindrome or not.
- The method uses two pointers - left and right - to traverse the ArrayList from the start and end simultaneously.
- It compares the characters at the left and right positions in the ArrayList. If they are not equal, it means the ArrayList is not a palindrome, and the method returns false.
- If the loop finishes without finding any mismatch (i.e., left >= right), it means the ArrayList is a palindrome, and the method returns true.
In the example given, the output will be:
List 1 is a palindrome: true
List 2 is a palindrome: false
You can modify the characters1 and characters2 lists in the main method with your own input characters to test the program with different palindromes.

0 Comments