Question

Lab #4 – Recursive Methods for Generic ArrayList ----- JAVA The problem Use recursion to implement...

Lab #4 – Recursive Methods for Generic ArrayList ----- JAVA

  1. The problem

    Use recursion to implement some list functionalities on an ArrrayList of generic type using type parameters in method definition

    Our goal for this lab is to continue using the divide and conquer approach of splitting a list into its head and tail and keep recursing on the tail (which happens to be smaller). However, instead of trying the approach on a string (a list of characters) we would like to use an ArrayList of an arbitrary type of list element, parameterized by E. We can still use the same design outline as the previous lab exercise (Lab 3).

    Note the following prototype declaration for the ArrayList class:

         public class ArrayList<E>
         extends AbstractList<E>
         implements List<E>, ......
    

    Perform the following tasks in a class called ListRecursive

    Task #1 Develop a recursive method to reverse a list

    Develop a method with the prototype

           public static <E> void reverse (ArrayList<E> inputList)
    

    based on selecting the first list element as the head and the remaining list as its tail. Here is

    1. 1) Base case: The problem is trivial when the list size is 0 or 1.

    2. 2) Decomposition: For lists with size > 1:

      1. a) Extract its head (element) and leave the tail (the input list with the head removed). You can look up the method that does this for the List interface.

      2. b) Make a recursive call to obtain the tail reversed.

Page 1 of 3

3) Composition: Append the extracted head element to the reversed tail obtain the original list reversed.

Task #2 Develop a recursive method to find the maximal element

Note that this is not possible unless the list elements are comparable to each other. Java provides a generic Interface for this called Comparable<T>. Based on this, develop a method with the following prototype

public static <E extends Comparable<E>> E max(List<E> inputList)

You can use the same problem decomposition technique as in Task #1. Think about how the composition of result should be made.

Task #3 Develop a recursive method to sum the list elements

Obviously, this is not possible unless the list elements are of numeric type. Develop a recursive summing method with the prototype

public static <E extends Number> double sum (List<E> inputList)

Task #4 Use command line arguments to supply the list elements

Use the following main() method:

      public static void main(String args[]) {
          ArrayList<String> argList = new ArrayList<>();
          ArrayList<Double> numericArgs = new ArrayList<>();
          for (String s : args) {
             argList.add(s);
             try {
                numericArgs.add(Double.parseDouble(s));
             }
             catch (NumberFormatException e) {
                System.out.println(e.getMessage() + "is not
   numeric...skipping");
             }

}

          System.out.print("Command line arguments before
   reversal: ");
          for (int i=0; i<argList.size(); i++)
             System.out.print(argList.get(i)+ " ");
          System.out.println();
          reverse(argList);
          System.out.print("Command line arguments after
   reversal: ");

Page 2 of 3

for (int i=0; i<argList.size(); i++)
             System.out.print(argList.get(i)+ " ");
          System.out.println();
          System.out.println("Max of argument list is \"" +
   max(argList) + "\"");
          System.out.println("Sum of numeric arguments is \"" +
   sum(numericArgs) + "\"");

}

You should test your program with different command-line inputs and observe the results of passing different combinations of numeric and non-numeric values.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Java program to reverse an Array List using Recursion

import java.util.ArrayList;

import java.util.Iterator;

import java.util.List;

    public class recurse{

             private static List<String> l = new ArrayList<String>();

              private static List<String> reversedSet = new ArrayList<String>();

     public static void main(String[] args){

           List l=new ArrayList();

           System.out.println("Enter array values");                        //Input array values

           String a=input.nextLine();

               l.add(a);                                   //elements added to array list

               reverse( l );                         //recursive call to reverse the array list

               printList( reversedSet );            //function call to print the reversed array

        }

public static void reverse( List<String> listinp ) {  

       String firstele = null;

       if ( listinp.size() == 0 ) {                                 //If size of input array is 0 then no input

                  return;

       }

       else {

            firstele = listinp.get(0);                                         //first element of array list taken

            listinp.remove(0);                                            

        }

   reverseList( listinp );

   reversedSet.add( firstele );

   }

public static void printList( List<String> listinp ) {

    Iterator<String> listIterator = listinp.iterator();

    while( listIterator.hasNext() ) {

               String element = listIterator.next();

               System.out.println( element );                       //Reversed elements are printed

     }

}

}

Add a comment
Know the answer?
Add Answer to:
Lab #4 – Recursive Methods for Generic ArrayList ----- JAVA The problem Use recursion to implement...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • *Java* Hi. I need some help with creating generic methods in Java. Write a program GenMethods...

    *Java* Hi. I need some help with creating generic methods in Java. Write a program GenMethods that has the following generic methods: (1) Write the following method that returns a new ArrayList. The new list contains the nonduplicate (i.e., distinct) elements from the original list. public static ArrayList removeDuplicates(ArrayList list) (2) Write the following method that shuffles an ArrayList. It should do this specifically by swapping two indexes determined by the use of the random class (use Random rand =...

  • Study the recursive instance method length()of MyLinkedList2 class and its associated auxiliary method. Then solve (a),...

    Study the recursive instance method length()of MyLinkedList2 class and its associated auxiliary method. Then solve (a), (b), and (c) below in a similar way: (a)   Convert the method public Element find(Object obj)of MyLinkedList2 class to a recursive one. Use an auxiliary private method. (b)   Convert the method public String toString( )of MyLinkedList2 class to a recursive one such that it returns the string representation of a linked list in the form: {ValueDatum1  valueDatum2 valueDatum3  . . .  valueDatumN-1   valueDatumN} Use an auxiliary private method....

  • java Write a generic method that takes an ArrayList of objects (of a valid concrete object...

    java Write a generic method that takes an ArrayList of objects (of a valid concrete object type) and returns a new ArrayList containing no duplicate elements from the original ArrayList. The method signature is as follows: public static ArrayList UniqueObjects(ArrayList list) Test the method with at least 2 array lists of different concrete object types. Label your outputs properly and show the array lists content before and after calling method UniqueObjects

  • Check if an array is a heap in Java. Complete the method isHeapTree Together, these methods...

    Check if an array is a heap in Java. Complete the method isHeapTree Together, these methods are meant to determine if an array of objects corresponds to a heap. The methods are generic, and they should work with an array of any type T that implement Comparable<T>. Implement the second method so that it uses recursion to process the complete tree/subtree whose root is at position i in the array arr. The method should return true if that tree/subtree is...

  • Now, your objective is to rewrite the same Stack class with a Generic ArrayList and make...

    Now, your objective is to rewrite the same Stack class with a Generic ArrayList and make the entire class support using Generic types. You should be able to create a Stack of any primitive wrapper class, and show us that your Generic Stack implementation (push, pop, search, display, etc.) works with: • Character (Stack) • Integer (Stack) • Float (Stack • Double (Stack) • String (Stack) You can create these Stack objects in main() and perform operations on them to...

  • Here is the IntegerLinkedList_incomplete class: public class IntegerLinkedList { static class Node { /** The element...

    Here is the IntegerLinkedList_incomplete class: public class IntegerLinkedList { static class Node { /** The element stored at this node */ private int element; // reference to the element stored at this node /** A reference to the subsequent node in the list */ private Node next; // reference to the subsequent node in the list /** * Creates a node with the given element and next node. * * @param e the element to be stored * @param n...

  • Java implement the method in IteratorExercise.java using only list iterator methods: bubbleSort: sort the provided list...

    Java implement the method in IteratorExercise.java using only list iterator methods: bubbleSort: sort the provided list using bubble sort Do not modify the test code in each function. You can look at that code for some ideas for implementing the methods. import java.lang.Comparable; import java.util.*; public class IteratorExercise {       public static <E extends Comparable<? super E>> void bubbleSort(List<E> c) throws Exception {        // first line to start you off        ListIterator<E> iit = c.listIterator(), jit;...

  • A java exercise please! Write a static method named swapHavles that takes an ArrayList of integers...

    A java exercise please! Write a static method named swapHavles that takes an ArrayList of integers as a a parameter and returns a new ArrayList that has every element in the second half of the original ArrayList swapped with every element in the first half of the original ArrayList. Note: • You can assume that the ArrayList passed to this method as a parameter always contains an even number of elements and will always contain at least two elements. For...

  • "Java question" Implement a generic method that returns the minimum element in an array.        public...

    "Java question" Implement a generic method that returns the minimum element in an array.        public static<EextendsComparable<E>> E min(E[ ] list)

  • Problem 1 Given a linked list of integers, write a function getUnique that removes all duplicates elements in the linked list and returns the new linked list of unique elements (The order does not ma...

    Problem 1 Given a linked list of integers, write a function getUnique that removes all duplicates elements in the linked list and returns the new linked list of unique elements (The order does not matter). Example: Input: 1-»2->3->1-2 Output: 1->2->3 public class Node f int iterm Node next; Node(int d) t item = d; next-null; ) import java.util.ArrayList; public class ExtraLab public static void main (String[] args)t PROBLEM 1 System.out.println("PROBLEM 1"); Node head new Node(1); head.next-new Node (2); head.next.next-new Node(3);...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT