Question

Build two arrays[ ] (Integer and String) and convert them to two ArrayLists and write two...

Build two arrays[ ] (Integer and String) and convert them to two ArrayLists and write two overloaded generic static search method to find the index locations of a specified value. One of the search methods applies to the array type while the other (overloaded) search method applies to the collection type.

Implement the following generic linear search method and write a client program to display results:

(Here is the header)

public static <E extends Comparable<E>> int search(E[] list, E key) {

            // add codes here

      }

Write an overloaded search method to process the collection type.

The following code is included for the problem:

//This program runs in finding the location (index) of a name and number.
//For this question, convert the arrays to an ArrayList and write another overloaded search method to do the same.


public class MainClient {
   public static void main(String[] args) {
       Integer[] list = {2, 13, 41, 17, -12, 43, -21, 99, 0};
       String[] names = {"Corey", "Zeal", "Hannah", "Ain", "Star", "Larry", "who"};
// use enhanced for to print the list and names
       for (int i =0; i < list.length; i++) {
           System.out.print(list[i] + ", ");
       }
      
       System.out.println();
       System.out.println("looking for 99 index = " + search(list, 99));
       System.out.println("looking for \"who \" index= " + search(names, "who"));
   }
  
   // use the method provided to create two ArrayList from the above array list and names
  
  
  

   public static <E extends Comparable<E>> int search(E[] list, E key) {
       for (int i = 0; i < list.length; i++)
           if (list[i].equals(key))
               return i;
       return -1;
   }
  
   // write a generic search method that takes the generic collection parameters instead of a generic array
   // inside this search method use an enhance for-loop to find the key


  
  
  
  
  
   public static <T> void fromArrayToCollection(T a[], Collection<T> c) {
       for (T x: a)
           c.add(x);
   }
}

The search(….) method returns the location (array index loc) for the <E> key when a match found,

and -1 if there is no match.

Result Sample: Search for 199, and “who” for the array search; -12 and “where” for the collection type search.

2 13 41 17 -12 43 -21 199 -12 0

Corey Zeal Hannah Ain Star Larry who where

----- using generic/array search -------------

looking for the index of 199 = 7

looking for the index of "who": 6

----- using generic/collection search -------------

[Corey, Zeal, Hannah, Ain, Star, Larry, who, where]

looking for the index of "who " index = 6

[2, 13, 41, 17, -12, 43, -21, 199, -12, 0]

looking for the index of -12 = 4

Homework Answers

Answer #1

PROGRAM :

package arraylist;

import java.util.*;
// Defines class A6Q5
public class A6Q5
{
// main method definition
public static void main(String []s)
{
// Creates an Integer type array
Integer [] list = {2, 13, 41, 17, -12, 43, -21, 99, 0};
// Creates an String type array
String [] names = {"Austin", "Max", "Spencer", "Mattew", "Blake",
"Dakota", "who", "where"};

// Creates an array list of type Integer
ArrayList<Integer> listInt = new ArrayList<Integer>();
// Creates an array list of type String
ArrayList<String> listNames = new ArrayList<String>();

// Displays integer array
System.out.print("\n Integer Array: ");
// Loops till end of the list
for(int i = 0; i < list.length; i++)
System.out.print(list[i] + ", ");

// Displays integer array
System.out.print("\n String Array: ");
// Loops till end of the names
for(int i = 0; i < names.length; i++)
System.out.print(names[i] + ", ");

System.out.println("\n\n ------ Using generic / Array search ------");
// Calls the method to search 99 in list, and displays the returned result
System.out.println("Looking for 99 index = " + search(list, 99));
// Calls the method to search "who" in list, and displays the returned result
System.out.println("Looking for \"who\" index = " + search(names, "who"));

// Calls the method to convert integer array to array list of type integer
fromArrayToColection(list, listInt);
// Calls the method to convert string array to array list of type string
fromArrayToColection(names, listNames);

// Displays the integer type array list
System.out.println("\n Array list of Integer: " + listInt);
// Displays the string type array list
System.out.println("\n Array list of String: " + listNames);

System.out.println("\n ------ Using generic / Collection search ------");
// Calls the method to search -12 in array list of type integer
// and displays the returned result
System.out.println("Looking for -12 index = " + search(listInt, -12));
// Calls the method to search "where" in array list of type integer
// and displays the returned result
System.out.println("Looking for \"where\" index = " + search(listNames, "where"));
}// End of main method

// Generic method to search parameter key in the array
public static <E extends Comparable<E>> int search(E list[], E key)
{
// Loops till number of elements in the array
for(int i = 0; i < list.length; i++)
// Checks if current index position data is equals to parameter key
if (list[i].equals(key))
// Returns loop variable as found index
return i;
// Returns -1 for not found
return -1;
}// End of method

// Generic method to search parameter key in the array list
public static <M extends Comparable<M>> int search(ArrayList<M> list,
M key)
{
// Loops till number of elements in the array list
for(int i = 0; i < list.size(); i++)
// Checks if current index position data is equals to parameter key
if (list.get(i).equals(key))
// Returns loop variable as found index
return i;
// Returns -1 for not found
return -1;
}// End of method

// Generic method to convert first parameter array to second parameter array list
public static <T extends Comparable<T>> void fromArrayToColection(T a[], Collection<T> c)
{
// Enhanced for loop to extract each element from the array
for (T x : a)
// Adds the current element to array list
c.add(x);
}// End of method
}// End of class

Sample Output:


Integer Array: 2, 13, 41, 17, -12, 43, -21, 99, 0,
String Array: Austin, Max, Spencer, Mattew, Blake, Dakota, who, where,

------ Using generic / Array search ------
Looking for 99 index = 7
Looking for "who" index = 6

Array list of Integer: [2, 13, 41, 17, -12, 43, -21, 99, 0]

Array list of String: [Austin, Max, Spencer, Mattew, Blake, Dakota, who, where]

------ Using generic / Collection search ------
Looking for -12 index = 4
Looking for "where" index = 7

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
Build two simple arrays (Integer and String) of 6 in length. Convert the two arrays into...
Build two simple arrays (Integer and String) of 6 in length. Convert the two arrays into a List type using an ArrayList type. A static method Array2Collection generic method is provided for that. From the List, display the contents of the two arrays in the forward or backward order: (without using an index for loop) //Code for converting Array to a Collection type static <T> void Array2Collection(T[] a, Collection<T> c) {     for (T x : a) {         c.add(x);...
[Java] I'm not sure how to implement the code. Please check my code at the bottom....
[Java] I'm not sure how to implement the code. Please check my code at the bottom. In this problem you will write several static methods to work with arrays and ArrayLists. Remember that a static method does not work on the instance variables of the class. All the data needed is provided in the parameters. Call the class Util. Notice how the methods are invoked in UtilTester. public static int min(int[] array) gets the minimum value in the array public...
Java question, Please answer everything. Thank you Answer the following questions as briefly (but completely) as...
Java question, Please answer everything. Thank you Answer the following questions as briefly (but completely) as possible: What is a checked exception, and what is an unchecked exception? What is NullPointerException? Which of the following statements (if any) will throw an exception? If no exception is thrown, what is the output? 1: System.out.println( 1 / 0 ); 2: System.out.println( 1.0 / 0 ); Point out the problem in the following code. Does the code throw any exceptions? 1: long value...
JAVA please Arrays are a very powerful data structure with which you must become very familiar....
JAVA please Arrays are a very powerful data structure with which you must become very familiar. Arrays hold more than one object. The objects must be of the same type. If the array is an integer array then all the objects in the array must be integers. The object in the array is associated with an integer index which can be used to locate the object. The first object of the array has index 0. There are many problems where...
THIS IS FOR JAVA I have to write a method for a game of Hangman. The...
THIS IS FOR JAVA I have to write a method for a game of Hangman. The word the user is trying to guess is made up of hashtags like so " ###### " If the user guesses a letter correctly then that letter is revealed on the hashtags like so "##e##e##" If the user guesses incorrectly then it increments an int variable named count " ++count; " String guessWord(String guess,String word, String pound) In this method, you compare the character(letter)...
Write code in java Implement a method to build an AVL tree out of a sorted...
Write code in java Implement a method to build an AVL tree out of a sorted (ascending order) array of unique integers, with the fastest possible big O running time. You may implement private helper methods as necessary. If your code builds a tree that is other than an AVL tree, you will not get any credit. If your code builds an AVL tree, but is not the fastest big O implementation, you will get at most 12 points. You...
Write a loop that sets each array element to the sum of itself and the next...
Write a loop that sets each array element to the sum of itself and the next element, except for the last element which stays the same. Be careful not to index beyond the last element. Ex: Initial Scores: 10, 20, 30, 40 Scores after loop: 30, 50, 70, 40 Import. java.util.Scanner; public class StudentScores { public static void main (String [] args){ Scanner scnr = new Scanner (System.in); final int SCORES_SIZE = 4; int [] bonusScores = new int[SCORES_SIZE]; int...
8.15 *zyLab: Method Library (Required & Human Graded) This code works but there are some problems...
8.15 *zyLab: Method Library (Required & Human Graded) This code works but there are some problems that need to be corrected. Your task is to complete it to course style and documentation standards CS 200 Style Guide. This project will be human graded. This class contains a set of methods. The main method contains some examples of using the methods. Figure out what each method does and style and document it appropriately. The display method is done for you and...
Do a theta analysis and count the number of computations it performed in each function/method of...
Do a theta analysis and count the number of computations it performed in each function/method of the following code: import java.io.*; import java.util.Scanner; class sort { int a[]; int n; long endTime ; long totalTime; long startTime; static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public sort(int nn) // Constructor { a = new int[nn]; n = nn; endTime= 0; totalTime =0; startTime =0; } public static void main(String args[]) throws IOException { System.out.print("\nEnter number of students: "); int nn =...
This laboratory assignment involves implementing a data structure called a map. A map associates objects called...
This laboratory assignment involves implementing a data structure called a map. A map associates objects called keys with other objects called values. It is implemented as a Java class that uses arrays internally. 1. Theory. A map is a set of key-value pairs. Each key is said to be associated with its corresponding value, so there is at most one pair in the set with a given key. You can perform the following operations on maps. You can test if...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT