Question

Introduction In this lab we are looking at using an ArrayList in place of a Linked List. You may not know all of the LinkedLi

Excellent: Explain why the change above causes the code to run faster for an ArrayList. Also explain why this was not necessa

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

public class ListPractice {
  
   private static final int[] arr = new int[100000];

   public static void main(String[] args) {
       for(int i=0; i<100000; i++)
           arr[i] = i;
      
       //TODO comment out this line
       LinkedList<Integer> list = new LinkedList<Integer>();
      
       //TODO uncomment this line
       //List<Integer> list = new ArrayList<Integer>();
      
       //TODO change the rest of the code as necessary to make this program work
      
       //let's generate some prime numbers
      
       //start with some numbers
       for(int i : arr)
           list.add(i);
       //compute the largest factor for these numbers
       int maxVal = list.getFirst();
       for(Integer i : list)
           if(i > maxVal)
               maxVal = i;
       int maxFactor = (int)Math.ceil(Math.sqrt(maxVal));
       //for every factor between 2 and maxFactor
       for(int factor = 2; factor <= maxFactor; factor++) {
           //check each Integer in the list
           int num = list.size();
           for(int i=0; i<num; i++) {
               //remove it
               Integer toCheck = list.removeFirst();
               //if it is not a multiple of factor, or is equal to factor, add it to the back
               if(toCheck == factor || toCheck % factor != 0)
                   list.addLast(toCheck);
           }
       }
       //print them out!
       while(!list.isEmpty())
           System.out.println(list.removeFirst());
   }

  

}

------------------------------

Please solve the program above by using java language.

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.util.List; import java.util.ArrayList; //import java.util.LinkedList; class ListPractice { private static final int[] arr = new int[100000]; public static void main(String[] args) { for(int i=0; i<100000; i++) arr[i] = i; //TODO comment out this line //LinkedList<Integer> list = new LinkedList<Integer>(); //TODO uncomment this line List<Integer> list = new ArrayList<Integer>(); //TODO change the rest of the code as necessary to make this program work //let's generate some prime numbers //start with some numbers for(int i : arr) list.add(i); //compute the largest factor for these numbers int maxVal = list.get(0);//update:passing index of first element to get() for(Integer i : list) if(i > maxVal) maxVal = i; int maxFactor = (int)Math.ceil(Math.sqrt(maxVal)); //for every factor between 2 and maxFactor for(int factor = 2; factor <= maxFactor; factor++) { //check each Integer in the list int num = list.size(); for(int i=0; i<num; i++) { //remove it Integer toCheck = list.get(i); // update: passing index to get() ith element from list //if it is not a multiple of factor, or is equal to factor, add it to the back if(toCheck != factor && toCheck % factor == 0) { list.remove(i); i--; num--; } } } //print them out! for(int i=0;i<list.size();i++) System.out.println(list.get(i)); } }

Above code contains all the necessary changes to use ArrayList replacing LinkedList.

getFirst(), addLast() & removeFirst(): these methods are not available for ArrayList.

I have used below methods of ArrayList:

get(int index) to retrieve i-th element (0 based index) and remove(int index) to delete element from i-th index.

remove() operation is expensive in ArrayList in terms of time because after every deletion, all the elements to the right of deleted element are shifted to the left by 1.

So instead of removing element every time and adding it again, I have updated the condition to check if current element shoud be deleted or not. If condition is true then the element will be deleted once and no addition operation is needed now and after deleting element decrement the size and index by 1 because size will be reduced by 1 and also the elements will be shifted to the left by 1.

Finally to print the elements, call get() on list and print the value returned by this method.

ArraList is based on indexing hence retrieval is achieved in constant time (O(1)) which is much better than LinkedList where it is O(n).

Older code was also faster because remove operation in LinkedList can be done in much lesser time than in ArrayList because no shifting of elements is required after removing element from LinkedList. That is why without optimization previous code was still working fine. So if we change LinkedList to ArrayList simply without optimizing remove and add operations, it will take too much of time to execute and print the result. Hence with ArrayList, this optimization is required.

As a summary, i have reduced remove operations (expensive) and removed add operation again and again. To retrieve the element from list used get() method instead of calling remove() method.

Add a comment
Know the answer?
Add Answer to:
import java.util.List; import java.util.ArrayList; import java.util.LinkedList; public class ListPractice {       private static final int[]...
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
  • package week_4; import input.InputUtils; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Random; import static input.InputUtils.positiveIntInput; import static input.InputUtils.yesNoInput;...

    package week_4; import input.InputUtils; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Random; import static input.InputUtils.positiveIntInput; import static input.InputUtils.yesNoInput; /** Write a program to roll a set of dice. Generate a random number between 1 and 6 for each dice to be rolled, and save the values in an ArrayList. Display the total of all the dice rolled. In some games, rolling the same number on all dice has a special meaning. In your program, check if all dice have the same value,...

  • import java.util.ArrayList; import java.util.List; public abstract class AbstractBoxPacking { protected List input; protected int boxSize; public...

    import java.util.ArrayList; import java.util.List; public abstract class AbstractBoxPacking { protected List input; protected int boxSize; public AbstractBoxPacking(List input, int boxSize){ this.input = input; this.boxSize = boxSize; } public abstract int getOutput(); public List deepCopy(List boxes){ ArrayList copy = new ArrayList(); for(int i = 0; i < boxes.size(); i++){ copy.add(boxes.get(i).deepCopy()); } return copy; } } I need Help fixing the errors in my java code

  • import java.util.LinkedList; public class testprintOut { private static LinkedList[] array; public static void main(String[] args) {...

    import java.util.LinkedList; public class testprintOut { private static LinkedList[] array; public static void main(String[] args) { int nelems = 5; array = new LinkedList[nelems]; for (int i = 0; i < nelems; i++) { array[i] = new LinkedList<String>(); } array[0]=["ab"]; System.out.println(array[0]); } } //I want to create array of linked lists so how do I create them and print them out efficiently? //Syntax error on token "=", Expression expected after this token Also, is this how I can put them...

  • /** * */ package groceries; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ShoppingList {   ...

    /** * */ package groceries; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ShoppingList {    /**    * @param args    */    public static void main(String[] args) {        List groceryList = new ArrayList<>();        groceryList.add("rice");        groceryList.add("chicken");        groceryList.add("cumin");        groceryList.add("tomato");        groceryList.add("cilantro");        groceryList.add("lime juice");        groceryList.add("peppers");               groceryList.remove("cilantro");               for (int i = 0; i            if (groceryList.get(i).equals("peppers")) {...

  • //MultiValuedTreeMap.java import java.util.Iterator; import java.util.LinkedList; import java.util.TreeMap; //import java.util.ArrayList; public class MultiValuedTreeMap<K, V> extends TreeMap<K, LinkedList<V>>...

    //MultiValuedTreeMap.java import java.util.Iterator; import java.util.LinkedList; import java.util.TreeMap; //import java.util.ArrayList; public class MultiValuedTreeMap<K, V> extends TreeMap<K, LinkedList<V>> implements Iterable<Pair<K, V>> {    private static final long serialVersionUID = -6229569372944782075L;       public void add(K k, V v) { // Problem 1 method        // empty linked list, with key=k         if (!containsKey(k)) {               put(k, new LinkedList<V>());         }         // adding v to the linked list associated with key k         get(k).add(v);    }    public V removeFirst(K k)...

  • import java.util.ArrayList; import java.util.List; import java.util.Stack; public class Main { public static void main(String[] args) {...

    import java.util.ArrayList; import java.util.List; import java.util.Stack; public class Main { public static void main(String[] args) { int programCounter = 0; List<String> program = new ArrayList<String>(); Stack<String> stack = new Stack<String>(); // TODO string probably not best program.add("GOTO start<<1>>"); program.add("LABEL Read"); program.add("LINE -1"); program.add("FUNCTION Read -1 -1"); program.add("READ"); program.add("RETURN "); program.add("LABEL Write"); program.add("LINE -1"); program.add("FUNCTION Write -1 -1"); program.add("FORMAL dummyFormal 0"); program.add("LOAD 0 dummyFormal"); program.add("WRITE"); program.add("RETURN "); program.add("LABEL start<<1>>"); program.add("LINE 1"); program.add("FUNCTION main 1 4"); program.add("LIT 0 i"); program.add("LIT 0 j");...

  • package cards; import java.util.ArrayList; import java.util.Scanner; public class GamePlay { static int counter = 0; private...

    package cards; import java.util.ArrayList; import java.util.Scanner; public class GamePlay { static int counter = 0; private static int cardNumber[] = {1,2,3,4,5,6,7,8,9,10,11,12,13}; private static char suitName[] = { 'c', 'd', 'h', 's' }; public static void main(String[] args) throws CardException, DeckException, HandException { Scanner kb = new Scanner(System.in); System.out.println("How many Players? "); int numHands = kb.nextInt(); int cards = 0; if (numHands > 0) { cards = 52 / numHands; System.out.println("Each player gets " + cards + " cards\n"); } else...

  • JAVA programming 9.9 Ch 9, Part 2: ArrayList Searching import java.util.ArrayList; public class ArrayListSet {    ...

    JAVA programming 9.9 Ch 9, Part 2: ArrayList Searching import java.util.ArrayList; public class ArrayListSet {     /**      * Searches through the ArrayList arr, from the first index to the last, returning an ArrayList      * containing all the indexes of Strings in arr that match String s. For this method, two Strings,      * p and q, match when p.equals(q) returns true or if both of the compared references are null.      *      * @param s The string...

  • What is the output of the following program? import java.util.ArrayList; import java.util.Collections; import java.util.List; public class...

    What is the output of the following program? import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Test implements Comparable<Test> private String[] cast; public Test( String[] st) cast = st; public int compareTo( Test t) if ( cast.length >t.cast.length ) t return +1; else if cast.length < t.cast.length return -1; else return 0; public static void main( String[] args String[] a"Peter", "Paul", "Mary" String[] b_ { "Мое", ''Larry", "Curly", String [ ] c = { ·Mickey", "Donald" }; "Shemp" }; List<Test>...

  • //LinkedList import java.util.Scanner; public class PoD {    public static void main( String [] args )...

    //LinkedList import java.util.Scanner; public class PoD {    public static void main( String [] args ) { Scanner in = new Scanner( System.in ); LinkedList teamList = new LinkedList(); final int TEAM_SIZE = Integer.valueOf(in.nextLine()); for (int i=0; i<TEAM_SIZE; i++) { String newTeamMember = in.nextLine(); teamList.append(newTeamMember); } while (in.hasNext()) { String removeMember = in.nextLine(); teamList.remove(removeMember); }    System.out.println("FINAL TEAM:"); System.out.println(teamList); in.close(); System.out.print("END OF OUTPUT"); } } =========================================================================================== //PoD import java.util.NoSuchElementException; /** * A listnked list is a sequence of nodes with...

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