100k views
2 votes
Provide a static method that checks whether a generic array list is a palindrome; that is, whether the values at index i and n - 1 - i are equal to each other, where n is the size of the array list.

User Duemir
by
6.3k points

1 Answer

3 votes

Answer:

Following are the code to these questions:

import java.util.*;//import package for user input

public class Main//defining a class

{

public static void main(String ab[])//defining main method

{

ArrayList<String> Val1 = new ArrayList<String>();//defining an ArrayList val

Val1.add("lunch");//use add method for add value

Val1.add("dinner");//use add method for add value

if(isPalindrome(Val1))// use if block to call method isPalindrome that accepts an array

{

System.out.println("Word in the list is palindrome.");//print message

}

else//defining else block

{

System.out.println("Word in the list is not a palindrome.");//print message

}

Iterator i1 = Val1.iterator();//creating iterator object to hold ArrayList value

while(i1.hasNext())//defining loop for count value

{

System.out.println(i1.next());//print value

}

}

public static<T> boolean isPalindrome(ArrayList<T> l)//defining method isPalindrome

l.size() == 1)//defining if block that check size value

return true;//return value

ArrayList<T> la = new ArrayList<T>(l.subList(1, l.size()-1));//defining an ArrayList la

return l.get(0).equals(l.get(l.size()-1)) && isPalindrome(la);//return value of ArrayList

}

Output:

Word in the list is not a palindrome.

lunch

dinner

Step-by-step explanation:

In the above code, an array list Val1 is declared, which uses the add method to store string value and after that, it uses a conditional statement to check its palindrome value. To check this, it defined a method that is "isPalindrome", that accepts a string value and check by the given code and return its value.

User Matt Harasymczuk
by
6.7k points