Question

In: Computer Science

Find a method of ArrayList that is not in the List interface, specifically a method that...

Find a method of ArrayList that is not in the List interface, specifically a method that trims the internal array down to fit exactly. A Google search for this did work, but the JDK API of course is the definitive source.

  1. Give the method header for the method.
  2. Add a call to this method to TestArrayList.java (which is available online in TestArrayList.zip), and see that it compiles and runs fine. Now change the line creating the ArrayList to use type List<String>for its variable (List <String>array = ...), and add the needed import for List. What happens when you try to compile this new version? For the homework answer, give the output.
  3. Explain why the compilation failed in this case. Note that this method is hardly ever used, and shows an example of a technical method related to the implementation that is excluded from the more abstract interface.
  4. Show that you can leave the type of array as List for most of the program (which is good programming practice, since most of it only needs a List) and still call this special method by "downcasting" array to ArrayList just for this one call. We use downcasting when we want to access specific behaviors of a subtype not supported by the original type. In your homework submission, show the line of code with the downcast.

TestArrayList1

import java.util.ArrayList;

public class TestArrayList {

  public static void main( String [ ] args )

  {

     ArrayList<String> array = new ArrayList<String>();

     array.add("apple");

     array.add("banana");

    // Loop through the collection by index

    for ( int i = 0; i < array.size( ); i++ )  {

        System.out.println( array.get( i ) );

    }

    // Using the fact that Collections are Iterable

    for (String s: array) {

        System.out.println(s);

    }

  }

}

TestArrayList2

import java.util.ArrayList;

import java.util.Iterator;

public class TestArrayList2 {

  public static void main( String [ ] args )

  {

     ArrayList<String> array = new ArrayList<String>();

     array.add("apple");

     array.add("banana");

    // Loop through the collection by using an Iterator

     Iterator<String> itr = array.iterator();

     while (itr.hasNext()) {

         System.out.println(itr.next() );

    }

  }

}

TestArrayList3

import java.util.ArrayList;

import java.util.ListIterator;

public class TestArrayList3 {

  public static void main( String [ ] args )

  {

     ArrayList<String> array = new ArrayList<String>();

     array.add("apple");

     array.add("banana");

     // Loop through the collection by using a ListIterator

     ListIterator<String> itr = array.listIterator();

     while (itr.hasNext()) {

         System.out.println(itr.next() );

    }

    // going backwards:

    ListIterator<String> itr2 = array.listIterator(array.size());

     while (itr2.hasPrevious()) {

         System.out.println(itr2.previous() );

    }

    // The listIterator is still alive--

    System.out.println(itr2.next());

  }

}

TestArrayList4

import java.util.ArrayList;

import java.util.ListIterator;

class TestArrayList4

{

    public static void main( String [ ] args )

    {

        ArrayList<Integer> lst = new ArrayList<Integer>( );

        lst.add( 2 );

        lst.add( 4 );      

        ListIterator<Integer> itr1 = lst.listIterator( 0 );

   System.out.print( "Forward: " );

       while( itr1.hasNext( ) )

            System.out.print( itr1.next( ) + " " );

       System.out.println( );             

        System.out.print( "Backward: " );

        while( itr1.hasPrevious( ) )

             System.out.print( itr1.previous( ) + " " );

        System.out.println( );       

        System.out.print( "Backward: " );

        ListIterator<Integer> itr2 =

           lst.listIterator( lst.size( ) );

        while( itr2.hasPrevious( ) )

             System.out.print( itr2.previous( ) + " " );    

        System.out.println( );       

  System.out.print( "Forward: ");

for( Integer x : lst )

System.out.print( x + " " );

System.out.println( );

}

}

Solutions

Expert Solution

a) Give the method header for the method

Answer: public void trimToSize()

b) Add a call to this method to TestArrayList.java.

Answer: Please see the updated code below:

import java.util.ArrayList;

public class TestArrayList {
        public static void main(String[] args) {
                ArrayList<String> array = new ArrayList<String>();
                array.add("apple");
                array.add("banana");
                
                //trimming to size
                array.trimToSize();
                
                // Loop through the collection by index
                for (int i = 0; i < array.size(); i++) {
                        System.out.println(array.get(i));
                }
                // Using the fact that Collections are Iterable
                for (String s : array) {
                        System.out.println(s);
                }
                
        }
}

Now change the line creating the ArrayList to use type List<String>for its variable (List <String>array = ...), and add the needed import for List. What happens when you try to compile this new version? and c) Explain why the compilation failed in this case

Answer: The updated code is below, which will not compile because trimToSize method is specific to ArrayList only, List interface does not have declaration for this method, and when you change the type of array object to List from ArrayList, the array object can call only those methods defined in List interface without typecast.

import java.util.ArrayList;
import java.util.List;

public class TestArrayList {
        public static void main(String[] args) {
                List<String> array = new ArrayList<String>();
                array.add("apple");
                array.add("banana");
                
                //trimming to size
                array.trimToSize();
                
                // Loop through the collection by index
                for (int i = 0; i < array.size(); i++) {
                        System.out.println(array.get(i));
                }
                // Using the fact that Collections are Iterable
                for (String s : array) {
                        System.out.println(s);
                }
                
        }
}

d) Show that you can leave the type of array as List for most of the program (which is good programming practice, since most of it only needs a List) and still call this special method by "downcasting" array to ArrayList just for this one call.

Answer: Please see the updated code below:

Note: The line: ((ArrayList<String>) array).trimToSize(); is where the downcast happens.


import java.util.ArrayList;
import java.util.List;

public class TestArrayList {
        public static void main(String[] args) {
                List<String> array = new ArrayList<String>();
                array.add("apple");
                array.add("banana");

                // trimming to size
                ((ArrayList<String>) array).trimToSize();

                // Loop through the collection by index
                for (int i = 0; i < array.size(); i++) {
                        System.out.println(array.get(i));
                }
                // Using the fact that Collections are Iterable
                for (String s : array) {
                        System.out.println(s);
                }

        }
}

Note: I have no idea why you have provided different versions of TestArrayList classes. The changes specified in this question can be applied to any of those classes. Since the class name is TestArrayList, I have only made changes to the first version you attached. Feel free to experiment with other versions and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks


Related Solutions

Is List type is an interface in the Java collections framework? Classes Vector, ArrayList, and LinkedList...
Is List type is an interface in the Java collections framework? Classes Vector, ArrayList, and LinkedList are the same data structure but implement data storage in different ways. Classes, that implement Map interface in Java collections framework are used for storing what type of data? Declare and instantiate a list of elements of type String. Name this list myArray. what type of data structure is Stack? LinkedList data structure in Java collections is implemented as doubly linked lists. In PriorityQueue...
import java.util.*; class Main { static ArrayList<String> list; public static List<String> createList(ArrayList<String> arrayList) { list =...
import java.util.*; class Main { static ArrayList<String> list; public static List<String> createList(ArrayList<String> arrayList) { list = arrayList; return list; } public static void printList(ArrayList<String> arrayList) { System.out.println("Printing in 4 ways\n"); // 1 System.out.println(arrayList); //2 for(String s:arrayList) System.out.print(s+" "); System.out.println(); //3 System.out.println(Arrays.deepToString(list.toArray())); //4 for(int i=0;i<arrayList.size();i++) System.out.print(arrayList.get(i)+" "); System.out.println(); } public static void filterList(ArrayList<String> arrayList) { System.out.println("Filtered in 2 ways\n"); ArrayList<String> copyArrayList = arrayList; //1 for(int i=0;i<arrayList.size();i++) { if(arrayList.get(i).contains("chuck")) { arrayList.remove(i); i--; } } System.out.println(arrayList); //2 copyArrayList.removeIf(str -> str.contains("chunk")); System.out.println(copyArrayList); }   ...
Java OVERVIEW This program primarily focuses on the implementation of a ArrayList type interface and the...
Java OVERVIEW This program primarily focuses on the implementation of a ArrayList type interface and the necessary methods to implement the ArrayList. It also includes polymorphism and class comparison. INSTRUCTIONS Your deliverable will be to turn in three files. The files will be named Card.java, PremiumCard.java and the last file will be called CardArrayList.java. For this assignment, any use of a data control structure other than a simple Arrary or String will result in no credit. I am aware that...
Develop the getSuggestions(ArrayList wordCountList) method as the base method of the class. Develop the countWords(ArrayList wordList)...
Develop the getSuggestions(ArrayList wordCountList) method as the base method of the class. Develop the countWords(ArrayList wordList) method to find the frequencies of all words in the text file. Develop the getWordList(File[] fileArray) method to get all words in the text file. Ignore the words that have 3 or less characters. Your customer wants you to develop a method that will find the sentences that contain a specific word. This is basically a word search, but your customer needs the list...
Method: ArrayList<Integer> diff(ArrayList<Integer> list1, ArrayList<Integer> list2) diff() method accepts two ArrayLists of Integer and returns the...
Method: ArrayList<Integer> diff(ArrayList<Integer> list1, ArrayList<Integer> list2) diff() method accepts two ArrayLists of Integer and returns the union of elements in two lists. For example: list1 contains elements [1, 2, 3, 4, 5] list2 contains elements [3, 4, 5, 6, 7] Diff() method should return an array list with elements [1, 2, 3, 4, 5, 6, 7].
Java: Determine the ouotput of this code ArrayList<String>list=new ArrayList<String>();             list.add("Namath");           &
Java: Determine the ouotput of this code ArrayList<String>list=new ArrayList<String>();             list.add("Namath");             list.add("Sauer");             list.add("Maynard");             list.add("Namath");             list.add("Boozer");             list.add("Snell");             list.add("Namath");             list.add("Atkinson");             list.add("Lammonds");             list.add("Dockery");             list.add("Darnold");             list.remove(2);             list.set(2, "Brady");             list.remove(2);             list.set(4,"Unitas");             list.add(1,"Lamomica");             list.add(3,"Hanratty");             list.remove("Namath");             list.remove(list.size()-1);             list.remove(2);             list.set(7, "Riggins");             Iterator iter = list.iterator();           while (iter.hasNext())         {   System.out.print(iter.next() + " ");                         }                     } }
Create a PoemDriver.java class with a main method. In the main method, create an ArrayList of...
Create a PoemDriver.java class with a main method. In the main method, create an ArrayList of Poem objects, read in the information from PoemInfo.txt and create Poem objects to populate the ArrayList. After all data from the file is read in and the Poem objects added to the ArrayList- print the contents of the ArrayList. Paste your PoemDriver.java text (CtrlC to copy, CtrlV to paste) into the open space before. You should not change Poem.java or PoemInfo.txt. Watch your time...
In Java Create an interface Create an interface Printing, which have a method getPageNumber () that...
In Java Create an interface Create an interface Printing, which have a method getPageNumber () that return page number of any printing. Create an abstract class named Novel that implements Printing. Include a String field for the novel's title and a double field for the novel price. Within the class, include a constructor that requires the novel title, and add two get methods--one that returns the title and one that returns the price. Include an abstract method named setPrice().. Create...
******IN JAVA******** I need the following interface implemented accordingly. It is a linked list. The interface...
******IN JAVA******** I need the following interface implemented accordingly. It is a linked list. The interface can be found below: List.java public interface List<T> extends Iterable<T> { /** * Insert an element at a specified location. * @param index * @param obj * @throws IndexOutOfBoundsException */ public void add(int index, T obj); /** * Append an object to the end of the list. * @param obj */ public boolean add(T obj); public void clear(); public boolean contains(T obj); /** *...
3.1 Write code that creates an ArrayList object named list and fills list with these numbers...
3.1 Write code that creates an ArrayList object named list and fills list with these numbers (using one or a pair of for or while loops): 0 1 2 3 4 0 1 2 3 4 3.2 Consider the ArrayList object named list containing these Integers: list = { 1, 2, 3, 4, 5, 4, 3, 2, 1, 0 } What are the contents of list after this loop completes? for (int i = 1; i < 10; ++i) {...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT