Write a method that searches a string in ArrayList. If the string is in the Arra
ID: 3583442 • Letter: W
Question
Write a method that searches a string in ArrayList. If the string is in the ArrayList, the index will
be return, otherwise, return -1.
Consider the following code
ArrayList<String> friends = new ArrayList<String> ();
friends.add (“Mary”);
friends.add (“James”);
friends.add (“Kevin”);
friends.add (1, “Tanya”);
Consider the method search defined below
public static int search (String key, ArrayList<String> a){
int count = 0;
String temp = a.get(count);
while (count < a.size () && !temp.equals(key)){
if count<a.size()-1 { //if remove it, wha's wrong?
count++;
temp = a.get(count);
}
if (count < a.size())
return count;
else
return -1;
}
Explanation / Answer
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static int search (String key, ArrayList<String> a)
{
int count = 0;
String temp = a.get(count);
while (count < a.size() )
{
/*System.out.printf("%s ",a.get(count));
System.out.printf("count = %d ",count);
System.out.printf("temp = %s ",temp);*/
if(temp.equals(key))
{
return count;
}
count++;
if(count<a.size())
temp = a.get(count);
}
return -1;
}
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
ArrayList<String> friends = new ArrayList<String> ();
friends.add ("Marry");
friends.add ("James");
friends.add ("Kevin");
friends.add (1, "Tanya");
//check if string is present in array list
String key = "Kevin";
int ret;
System.out.printf("ArrayList in main: ");
for(int i = 0; i <friends.size(); i++)
{
System.out.printf("%s ",friends.get(i));
}
if((ret = search(key,friends)) >= 0 )
{
System.out.printf(" The string %s is found at position %d", key,ret+1);
}
else
System.out.printf(" String %s is not found in ArrayList ",key);
}
}
--------------------------------------------------------------------------------------------------------------
output1:
ArrayList in main: Marry Tanya James Kevin
The string Marry is found at position 1
outpu2:
ArrayList in main: Marry Tanya James Kevin
The string Tanya is found at position 2
output3:
ArrayList in main: Marry Tanya James Kevin
String David is not found in ArrayList
output 4:
ArrayList in main: Marry Tanya James Kevin
The string Kevin is found at position 4
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.