Results 1 to 10 of 10
  1. #1
    SamJava_the_Hut is offline Senior Member
    Join Date
    Jul 2013
    Location
    Wisconsin, USA
    Posts
    100
    Rep Power
    0

    Default ArrayList ensureCapacity method is not working

    Hi. I'm having trouble adjusting my ArrayList size. This shouldn't be happening, as I'm using Java 8, and the other ArrayList methods and functionalities seem to be working fine.

    First, here is a version of the main method class that shows what is not working:
    Java Code:
    package samsExperiments;
    
    import java.util.Scanner;
    import java.util.Arrays;
    import SortingAlgorithms.*;
    import customExceptions.BuiltInExceptions;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Vector;
    import java.util.Hashtable;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.ListIterator;
    
    public class SamsExperimentsMain {
    	
    	public static void main(String[] args){		
    		
    		System.out.println("Enter a string to convert to a Character ArrayList.");
    		Scanner a = new Scanner(System.in);
    		String myStr = a.nextLine();
    		
    		ArrayList<Character> strToChars = new ArrayList<>(20);		
    		System.out.println("The expected initial size of strToChars is 20.");
    		System.out.println("The actual initial size of strToChars is " + strToChars.size());
    		strToChars.ensureCapacity(25);
    		System.out.println("The expected new size of strToChars is 25.");
    		System.out.println("The actual new size of strToChars is " + strToChars.size());
    		for(int x = 0; x < myStr.length(); x++) {
    			strToChars.add(myStr.charAt(x));
    			if(x == myStr.length()) {
    				System.out.println("So far, we have: " + strToChars + ", which is " + strToChars.size() + " elements.");
    				System.out.println("We will now attempt to fill the rest of strToChars with 'x':");
    				while(x < strToChars.size()) {//put 'x' for the remaining empty index positions in strToChars
    					strToChars.add('x');
    				}				
    			}
    		}
    		System.out.println();
    		System.out.println("Assuming our string is hello world, we are expecting: ");
    		System.out.println("[h, e, l, l, o,  , w, o, r, l, d, x, x, x, x, x, x, x, x, x, x, x, x, x, x]");
    		System.out.println();
    		System.out.println("What we actually have is: ");
    		System.out.println(strToChars);
    		System.out.println();
    		
    		//A different list to verify whether the ensureCapacity ArrayList method works:
    		System.out.println("Now for Another ArrayList example that adds elements and increases " +
    							"its size manually in the process:");
    		ArrayList<String> list = new ArrayList<>(2);
            
            list.add("A");
            list.add("B");
             
            System.out.println(list);
             
            list.ensureCapacity(20);
            System.out.println("Our new size should be 20, yet it is still = " + list.size());
             
            list.add("C");
            list.add("D");
            list.add("E");
     
            System.out.println(list);
            System.out.println("After populating a our list with a few elements, the size is now = " + list.size());		
    		
    	}//end of main method	
    	
    }//end of class
    Output Sample:
    Enter a string to convert to a Character ArrayList.
    hello world
    The expected initial size of strToChars is 20.
    The actual initial size of strToChars is 0
    The expected new size of strToChars is 25.
    The actual new size of strToChars is 0

    Assuming our string is hello world, we are expecting:
    [h, e, l, l, o, , w, o, r, l, d, x, x, x, x, x, x, x, x, x, x, x, x, x, x]

    What we actually have is:
    [h, e, l, l, o, , w, o, r, l, d]

    Now for Another ArrayList example that adds elements and increases its size manually in the process:
    [A, B]
    Our new size should be 20, yet it is still = 2
    [A, B, C, D, E]
    After populating a our list with a few elements, the size is now = 5


    If anybody can figure out why the ensureCapacity ArrayList method is not working, or give me an alternate working solution, it will probably solve all of my problems.

    Although the add method statements on lines 57 to 59 did successfully increase the size of the list from 2 to 5, that will not work for my true motivations and purposes. I need to be able to dynamically change the size of the ArrayList, because I want to be able to fix any bad string that the user enters in, regardless of whether the good string (that will overwrite the bad string) and the bad string are different lengths, which also means that I can't use regular arrays for this project. That being said, here is the version of the main method that calls the code in my FixString class:
    Java Code:
    package samsExperiments;
    
    import java.util.Scanner;
    import java.util.Arrays;
    import SortingAlgorithms.*;
    import customExceptions.BuiltInExceptions;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Vector;
    import java.util.Hashtable;
    import java.util.Map;
    import java.util.HashMap;
    import java.util.LinkedList;
    import java.util.ListIterator;
    
    public class SamsExperimentsMain {
    	
    	public static void main(String[] args){		
    		
    		SamsDataStructures x = new SamsDataStructures();
    
    		FixString z = new FixString();
    		 
    		System.out.println("What is the bad string?");
    		Scanner a = new Scanner(System.in);
    		String badStr = a.nextLine();
    		System.out.println("What do you want the string to be?");
    		Scanner b = new Scanner(System.in);
    		String goodStr = b.nextLine();
    		String backToStr = z.fixBadStrWithArrayList(badStr, goodStr);
    		System.out.println("Our bad string is now changed to: " + backToStr);					
    		
    	}//end of main method	
    	
    }//end of class
    FixString.java
    Java Code:
    package samsExperiments;
    import java.util.Scanner;
    import java.util.ArrayList;
    import java.lang.StringBuilder;
    
    public class FixString {		
    	
    	public String fixBadStrWithArrayList(String badStr, String goodStr) {
    		ArrayList<Character> badStrToChars = new ArrayList<>();
    		for(int x = 0; x < badStr.length(); x++) {
    			badStrToChars.add(badStr.charAt(x));			
    		}
    		int badSize = badStrToChars.size();
    				
    		//Make a copy of the original badStrToChars for verification purposes:
    		ArrayList<Character> originalBadStrToChars = (ArrayList<Character>) badStrToChars.clone();//shallow copy
    		int originalBadSize = originalBadStrToChars.size();
    				
    		ArrayList<Character> goodStrToChars = new ArrayList<>();
    		for(int y = 0; y < goodStr.length(); y++) {
    			goodStrToChars.add(goodStr.charAt(y));
    		}
    		int goodSize = goodStrToChars.size();		
    		
    		boolean badSmallerThanGood = false;
    		if(badStrToChars.size() < goodStrToChars.size()) {//If the goodStr (which will overwrite the badStr) is
    														  //longer than the badStr, then we need to make room in
    														  //the badStr for the chars that need to be added to make
    														  //the badStr the same as goodStr.
    			
    			badSmallerThanGood = true;//This will enable a print statement further down in this class.
    			
    			int sizeDifference = goodSize - badSize;//Find the number of index positions needed to make the
    													//badStrToChars the correct length to accommodate for the
    													//extra chars needed to make it equivalent to goodStrToChars.
    			badStrToChars.ensureCapacity(badSize + sizeDifference);			
    			System.out.println("New badStrToChar size = " + badStrToChars.size());
    			
    			//Fill the newly added badStrToChars index positions with 'x' as a placeholder for now:
    			for(int i = originalBadSize; i <= badStrToChars.size()-1; i++) {
    				badStrToChars.add('x');//badStrToChars.set(i, 'x');
    			}
    			//Find out if the 'x' placeholders where added successfully:
    			for(char c : badStrToChars) {
    				System.out.print("[" + c + "]");
    				//Assuming the badStr String entered by the user was "hello world", 
    				//and the badStrToChars new size was set to 15, then we would expect 
    				//this enhanced for loop to print out:
    				//[h][e][l][l][o][ ][w][o][r][l][d][x][x][x][x]
    				
    				//Of course in this case, the x chars would eventually be overwritten by the last
    				//four chars in the goodStrToChars.
    			}
    			System.out.println();
    		}
    		
    		for(int i = 0; i < badStrToChars.size()-1; i++) {
    			
    			if(badStrToChars.get(i) != goodStrToChars.get(i)) {//if the current badStr char is not what it's 
    															   //supposed to be (if the char in the current 
    															   //badStrToChars index position is not the same  
    															   //as the char in the same index position of the
    															   //goodStrToChars),
    				badStrToChars.set(i, goodStrToChars.get(i));//then replace the badStrToChars char with the
    															//goodStrToChars char.
    			}
    			System.out.println("char at index [" + i + "] = " + badStrToChars.get(i));
    		}
    		int newBadSize = badStrToChars.size();//verify the size of the newly overwritten badStrToChar ArrayList
    		
    		//If the overwritten badStrToChars is longer than the goodStrToChars
    		if(badStrToChars.size() > goodStrToChars.size()) {//if there are still extra chars that don't belong there
    														  //(which will happen if the badStr is longer than the 
    														  //goodStr),
    			System.out.println("Original Bad String:        " + originalBadStrToChars);
    			System.out.println("Overwritten Bad String:     " + badStrToChars);
    			badStrToChars.subList(goodSize, badStrToChars.size()).clear();//then trim them off the fixed badStr.
    			System.out.println("Trimmed Bad String:         " + badStrToChars);			
    		}
    		
    		System.out.println();
    		
    		//If the badStr is shorter than the goodStr, remember that we already adjusted the badStrToChars size
    		//and put x char place holders in the if statement earlier. Needless to say, we don't need to trim any
    		//chars off of badStrToChars in this case. This print statement verifies that the badStrToChars was
    		//overwritten by goodStrToChars correctly.
    		if(badSmallerThanGood == true) {
    			System.out.println("Original Bad String:        " + originalBadStrToChars + " size = " + originalBadSize);
    			System.out.println("Overwritten Bad String:     " + badStrToChars + " size = " + newBadSize);
    		}
    		//Allow the now overwritten and adjusted badStrToChars ArrayList to become an official string,
    		//so that we can return as a string:
    		StringBuilder str = new StringBuilder();
    		for(char z : badStrToChars) {
    			str.append(z);
    		}
    		String backToStr = String.valueOf(str);
    		return backToStr;//return the overwritten, adjusted, and converted version of the badStr
    	}
    }//end of FixString class
    Here is an output sample that shows what happens if badStr > goodStr:
    What is the bad string?
    holllo werld
    What do you want the string to be?
    hello world
    The expected initial size of badStrToChars is 0
    char at index [0] = h
    char at index [1] = e
    char at index [2] = l
    char at index [3] = l
    char at index [4] = o
    char at index [5] =
    char at index [6] = w
    char at index [7] = o
    char at index [8] = r
    char at index [9] = l
    char at index [10] = d
    Original Bad String: [h, o, l, l, l, o, , w, e, r, l, d]
    Overwritten Bad String: [h, e, l, l, o, , w, o, r, l, d, d]
    Trimmed Bad String: [h, e, l, l, o, , w, o, r, l, d]

    Our bad string is now changed to: hello world

    And here is an output sample that shows what happens if badStr < goodStr:
    What is the bad string?
    hello world
    What do you want the string to be?
    holllo werld
    The expected initial size of badStrToChars is 0
    New badStrToChar size = 11
    [h][e][l][l][o][ ][w][o][r][l][d]
    char at index [0] = h
    char at index [1] = o
    char at index [2] = l
    char at index [3] = l
    char at index [4] = l
    char at index [5] = o
    char at index [6] =
    char at index [7] = w
    char at index [8] = e
    char at index [9] = r

    Original Bad String: [h, e, l, l, o, , w, o, r, l, d] size = 11
    Overwritten Bad String: [h, o, l, l, l, o, , w, e, r, d] size = 11

    Our bad string is now changed to: holllo werd


    As you can see, the ensureCapacity didn't do a damn thing in the second output example. And as a strange bonus, the l was taken out of werld, and the last d element was added somehow. Solving the ArrayList size adjustment issues will be the answer to my problems. If anybody knows what's going on, I would more than appreciate your help.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: ArrayList ensureCapacity method is not working

    ensureCapacity didn't do a damn thing
    The method is used to set the size of the internal storage for the list to keep from having to reallocate the internal storage when the current storage is exceeded.
    It has nothing to do with the list's size which is a count of the items in the list.

    Normally you do not need to consider or set the list's capacity. It is an efficiency thing.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    SamJava_the_Hut is offline Senior Member
    Join Date
    Jul 2013
    Location
    Wisconsin, USA
    Posts
    100
    Rep Power
    0

    Default Re: ArrayList ensureCapacity method is not working

    Quote Originally Posted by Norm View Post
    It has nothing to do with the list's size which is a count of the items in the list.
    I don't like the sound of that

    Do you have any suggestions whatsoever on how to redo this part of the code then?
    Java Code:
    boolean badSmallerThanGood = false;
            if(badStrToChars.size() < goodStrToChars.size()) {//If the goodStr (which will overwrite the badStr) is
                                                              //longer than the badStr, then we need to make room in
                                                              //the badStr for the chars that need to be added to make
                                                              //the badStr the same as goodStr.
                 
                badSmallerThanGood = true;//This will enable a print statement further down in this class.
                 
                int sizeDifference = goodSize - badSize;//Find the number of index positions needed to make the
                                                        //badStrToChars the correct length to accommodate for the
                                                        //extra chars needed to make it equivalent to goodStrToChars.
                badStrToChars.ensureCapacity(badSize + sizeDifference);         
                System.out.println("New badStrToChar size = " + badStrToChars.size());
                 
                //Fill the newly added badStrToChars index positions with 'x' as a placeholder for now:
                for(int i = originalBadSize; i <= badStrToChars.size()-1; i++) {
                    badStrToChars.add('x');//badStrToChars.set(i, 'x');
                }
                //Find out if the 'x' placeholders where added successfully:
                for(char c : badStrToChars) {
                    System.out.print("[" + c + "]");
                    //Assuming the badStr String entered by the user was "hello world", 
                    //and the badStrToChars new size was set to 15, then we would expect 
                    //this enhanced for loop to print out:
                    //[h][e][l][l][o][ ][w][o][r][l][d][x][x][x][x]
                     
                    //Of course in this case, the x chars would eventually be overwritten by the last
                    //four chars in the goodStrToChars.
                }
                System.out.println();
            }

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: ArrayList ensureCapacity method is not working

    how to redo this part of the code
    Can you explain what is wrong with the code?
    What do you want it to do differently?
    Post its current output
    and the desired output.

    How are you trying to debug the code so you can see what it is doing and how to change it for the desired results?
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    SamJava_the_Hut is offline Senior Member
    Join Date
    Jul 2013
    Location
    Wisconsin, USA
    Posts
    100
    Rep Power
    0

    Default Re: ArrayList ensureCapacity method is not working

    Norm, the problem is resizing the ArrayList. Right now, the enhanced for loop on line 20 is causing only the chars copied from the badStr string to the badStrToChars ArrayList, and the for loop on line 16 is not populating the would-be additional array positions with an 'x', because the statement on line 12 did not successfully resize the badStrToChars to provide the additional array positions for them in the first place:
    Java Code:
    boolean badSmallerThanGood = false;
            if(badStrToChars.size() < goodStrToChars.size()) {//If the goodStr (which will overwrite the badStr) is
                                                              //longer than the badStr, then we need to make room in
                                                              //the badStr for the chars that need to be added to make
                                                              //the badStr the same as goodStr.
                  
                badSmallerThanGood = true;//This will enable a print statement further down in this class.
                  
                int sizeDifference = goodSize - badSize;//Find the number of index positions needed to make the
                                                        //badStrToChars the correct length to accommodate for the
                                                        //extra chars needed to make it equivalent to goodStrToChars.
                badStrToChars.ensureCapacity(badSize + sizeDifference);         
                System.out.println("New badStrToChar size = " + badStrToChars.size());
                  
                //Fill the newly added badStrToChars index positions with 'x' as a placeholder for now:
                for(int i = originalBadSize; i <= badStrToChars.size()-1; i++) {
                    badStrToChars.add('x');//badStrToChars.set(i, 'x');
                }
                //Find out if the 'x' placeholders where added successfully:
                for(char c : badStrToChars) {
                    System.out.print("[" + c + "]");
                    //Assuming the badStr String entered by the user was "hello world", 
                    //and the badStrToChars new size was set to 15, then we would expect 
                    //this enhanced for loop to print out:
                    //[h][e][l][l][o][ ][w][o][r][l][d][x][x][x][x]
                      
                    //Of course in this case, the x chars would eventually be overwritten by the last
                    //four chars in the goodStrToChars.
                }
                System.out.println();
            }
    Read through the code comments in the code of my original post, and let me know if you need to know anything else.

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: ArrayList ensureCapacity method is not working

    the problem is resizing the ArrayList
    The only way to change the size (number of elements in the list) is to add or remove elements. Capacity is for efficiency.

    did not successfully resize the badStrToChars
    See the above.

    the for loop on line 16 is not populating the would-be additional array positions
    Make sure the loop is executing. Any call to the add method will result in an element being added to the list.
    Does the for loop execute?
    Last edited by Norm; 06-27-2019 at 02:43 PM.
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    SamJava_the_Hut is offline Senior Member
    Join Date
    Jul 2013
    Location
    Wisconsin, USA
    Posts
    100
    Rep Power
    0

    Default Re: ArrayList ensureCapacity method is not working

    Norm, I figured it out, thanks to the automatic resizing effect of adding elements to an ArrayList:

    Java Code:
    package samsExperiments;
    import java.util.Scanner;
    import java.util.ArrayList;
    import java.lang.StringBuilder;
    
    public class FixString {		
    	
    	public String fixBadStrWithArrayList(String badStr, String goodStr) {
    		ArrayList<Character> badStrToChars = new ArrayList<>();
    		for(int x = 0; x < badStr.length(); x++) {
    			badStrToChars.add(badStr.charAt(x));			
    		}
    		int badSize = badStrToChars.size();
    		
    				
    		//Make a copy of the original badStrToChars for verification purposes:
    		ArrayList<Character> originalBadStrToChars = (ArrayList<Character>) badStrToChars.clone();//shallow copy
    		int originalBadSize = originalBadStrToChars.size();
    				
    		ArrayList<Character> goodStrToChars = new ArrayList<>();
    		for(int y = 0; y < goodStr.length(); y++) {
    			goodStrToChars.add(goodStr.charAt(y));
    		}
    		int goodSize = goodStrToChars.size();		
    		
    		boolean badSmallerThanGood = false;
    		if(badStrToChars.size() < goodStrToChars.size()) {//If the goodStr (which will overwrite the badStr) is
    														  //longer than the badStr, then we need to make room in
    														  //the badStr for the chars that need to be added to make
    														  //the badStr the same as goodStr.
    			
    			
    			badSmallerThanGood = true;//This will enable a print statement further down in this class.
    			
    			int sizeDifference = goodSize - badSize;//Find the number of index positions needed to make the
    													//badStrToChars the correct length to accommodate for the
    													//extra chars needed to make it equivalent to goodStrToChars.
    			System.out.println("goodStrToChars size " + goodSize + " - badStrToChars size " + badSize +
    					" = a size difference of " + sizeDifference + " chars.");
    			
    			int newSizeGoal = badSize + sizeDifference;//add the size difference to the current badStrToChars size
    			
    			System.out.println("badStrToChars size " + badSize + " + sizeDifference " + sizeDifference +
    							   " = newSizeGoal of " + newSizeGoal);
    			
    			//Fill the newly added badStrToChars index positions with 'x' as a placeholder for now:
    			for(int i = badStrToChars.size()-1; i <= newSizeGoal-1; i++) {
    				badStrToChars.add('x');//badStrToChars.set(i, 'x');
    			}
    			
    			System.out.println("New badStrToChar size = " + badStrToChars.size());
    			
    			//Find out if the 'x' placeholders where added successfully:
    			for(char c : badStrToChars) {
    				System.out.print("[" + c + "]");
    				//Assuming the badStr String entered by the user was "hello world", 
    				//and the badStrToChars new size was set to 15, then we would expect 
    				//this enhanced for loop to print out:
    				//[h][e][l][l][o][ ][w][o][r][l][d][x][x][x][x]
    				
    				//Of course in this case, the x chars would eventually be overwritten by the last
    				//four chars in the goodStrToChars.
    			}
    			System.out.println();
    		}
    		
    		for(int i = 0; i < badStrToChars.size()-1; i++) {
    			
    			if(badStrToChars.get(i) != goodStrToChars.get(i)) {//if the current badStr char is not what it's 
    															   //supposed to be (if the char in the current 
    															   //badStrToChars index position is not the same  
    															   //as the char in the same index position of the
    															   //goodStrToChars),
    				badStrToChars.set(i, goodStrToChars.get(i));//then replace the badStrToChars char with the
    															//goodStrToChars char.
    			}
    			System.out.println("char at index [" + i + "] = " + badStrToChars.get(i));
    		}
    		int newBadSize = badStrToChars.size();//verify the size of the newly overwritten badStrToChar ArrayList
    		
    		//If the overwritten badStrToChars is longer than the goodStrToChars
    		if(badStrToChars.size() > goodStrToChars.size()) {//if there are still extra chars that don't belong there
    														  //(which will happen if the badStr is longer than the 
    														  //goodStr),
    			System.out.println("Original Bad String:        " + originalBadStrToChars);
    			System.out.println("Overwritten Bad String:     " + badStrToChars);
    			badStrToChars.subList(goodSize, badStrToChars.size()).clear();//then trim them off the fixed badStr.
    			System.out.println("Trimmed Bad String:         " + badStrToChars);			
    		}
    		
    		System.out.println();
    		
    		//If the badStr is shorter than the goodStr, remember that we already adjusted the badStrToChars size
    		//and put x char place holders in the if statement earlier. Needless to say, we don't need to trim any
    		//chars off of badStrToChars in this case. This print statement verifies that the badStrToChars was
    		//overwritten by goodStrToChars correctly.
    		if(badSmallerThanGood == true) {
    			System.out.println("Original Bad String:        " + originalBadStrToChars + " size = " + originalBadSize);
    			System.out.println("Overwritten Bad String:     " + badStrToChars + " size = " + newBadSize);
    		}
    		//Allow the now overwritten and adjusted badStrToChars ArrayList to become an official string,
    		//so that we can return as a string:
    		StringBuilder str = new StringBuilder();
    		for(char z : badStrToChars) {
    			str.append(z);
    		}
    		String backToStr = String.valueOf(str);
    		return backToStr;//return the overwritten, adjusted, and converted version of the badStr
    	}
    }//end of FixString class

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: ArrayList ensureCapacity method is not working

    Are these the expected results:
    Java Code:
            System.out.println("1="+fixBadStrWithArrayList("123", "45"));         // 1=45
            System.out.println("2="+fixBadStrWithArrayList("123", "456"));        // 2=453   ??? 
            System.out.println("3="+fixBadStrWithArrayList("123", "4567"));       // 3=4567
    The second one looks wrong.
    If you don't understand my response, don't ignore it, ask a question.

  9. #9
    SamJava_the_Hut is offline Senior Member
    Join Date
    Jul 2013
    Location
    Wisconsin, USA
    Posts
    100
    Rep Power
    0

    Default Re: ArrayList ensureCapacity method is not working

    Quote Originally Posted by Norm View Post
    Are these the expected results:
    Java Code:
            System.out.println("1="+fixBadStrWithArrayList("123", "45"));         // 1=45
            System.out.println("2="+fixBadStrWithArrayList("123", "456"));        // 2=453   ??? 
            System.out.println("3="+fixBadStrWithArrayList("123", "4567"));       // 3=4567
    The second one looks wrong.
    You're right again Norm. I provided a work around on lines 67 to 94 in the code below:
    Java Code:
    package samsExperiments;
    import java.util.Scanner;
    import java.util.ArrayList;
    import java.lang.StringBuilder;
    
    public class FixString {		
    	
    	public String fixBadStrWithArrayList(String badStr, String goodStr) {
    		ArrayList<Character> badStrToChars = new ArrayList<>();
    		for(int x = 0; x < badStr.length(); x++) {
    			badStrToChars.add(badStr.charAt(x));			
    		}
    		int badSize = badStrToChars.size();
    		
    				
    		//Make a copy of the original badStrToChars for verification purposes:
    		ArrayList<Character> originalBadStrToChars = (ArrayList<Character>) badStrToChars.clone();//shallow copy
    		int originalBadSize = originalBadStrToChars.size();
    				
    		ArrayList<Character> goodStrToChars = new ArrayList<>();
    		for(int y = 0; y < goodStr.length(); y++) {
    			goodStrToChars.add(goodStr.charAt(y));
    		}
    		int goodSize = goodStrToChars.size();		
    		
    		boolean badSmallerThanGood = false;
    		if(badStrToChars.size() < goodStrToChars.size()) {//If the goodStr (which will overwrite the badStr) is
    														  //longer than the badStr, then we need to make room in
    														  //the badStr for the chars that need to be added to make
    														  //the badStr the same as goodStr.
    			
    			
    			badSmallerThanGood = true;//This will enable a print statement further down in this class.
    			
    			int sizeDifference = goodSize - badSize;//Find the number of index positions needed to make the
    													//badStrToChars the correct length to accommodate for the
    													//extra chars needed to make it equivalent to goodStrToChars.
    			System.out.println("goodStrToChars size " + goodSize + " - badStrToChars size " + badSize +
    					" = a size difference of " + sizeDifference + " chars.");
    			
    			int newSizeGoal = badSize + sizeDifference;//add the size difference to the current badStrToChars size
    			
    			System.out.println("badStrToChars size " + badSize + " + sizeDifference " + sizeDifference +
    							   " = newSizeGoal of " + newSizeGoal);
    			
    			//Fill the newly added badStrToChars index positions with 'x' as a placeholder for now:
    			for(int i = badStrToChars.size()-1; i <= newSizeGoal-1; i++) {
    				badStrToChars.add('x');//badStrToChars.set(i, 'x');
    			}
    			
    			System.out.println("New badStrToChar size = " + badStrToChars.size());
    			
    			//Find out if the 'x' placeholders where added successfully:
    			for(char c : badStrToChars) {
    				System.out.print("[" + c + "]");
    				//Assuming the badStr String entered by the user was "hello world", 
    				//and the badStrToChars new size was set to 15, then we would expect 
    				//this enhanced for loop to print out:
    				//[h][e][l][l][o][ ][w][o][r][l][d][x][x][x][x]
    				
    				//Of course in this case, the x chars would eventually be overwritten by the last
    				//four chars in the goodStrToChars.
    			}
    			System.out.println();
    		}
    		
    		if(badStrToChars.size() == goodStrToChars.size()) {
    			for(int i = 0; i <= badStrToChars.size()-1; i++) {
    				
    				if(badStrToChars.get(i) != goodStrToChars.get(i)) {//if the current badStr char is not what it's 
    																   //supposed to be (if the char in the current 
    																   //badStrToChars index position is not the same  
    																   //as the char in the same index position of the
    																   //goodStrToChars),
    					badStrToChars.set(i, goodStrToChars.get(i));//then replace the badStrToChars char with the
    																//goodStrToChars char.
    				}
    				System.out.println("char at index [" + i + "] = " + badStrToChars.get(i));
    			}			
    		}
    		else if((badStrToChars.size() < goodStrToChars.size()) || (badStrToChars.size() > goodStrToChars.size())) {
    			for(int i = 0; i < badStrToChars.size()-1; i++) {
    				
    				if(badStrToChars.get(i) != goodStrToChars.get(i)) {//if the current badStr char is not what it's 
    																   //supposed to be (if the char in the current 
    																   //badStrToChars index position is not the same  
    																   //as the char in the same index position of the
    																   //goodStrToChars),
    					badStrToChars.set(i, goodStrToChars.get(i));//then replace the badStrToChars char with the
    																//goodStrToChars char.
    				}
    				System.out.println("char at index [" + i + "] = " + badStrToChars.get(i));
    			}			
    		}
    		int newBadSize = badStrToChars.size();//verify the size of the newly overwritten badStrToChar ArrayList
    		
    		//If the overwritten badStrToChars is longer than the goodStrToChars
    		if(badStrToChars.size() > goodStrToChars.size()) {//if there are still extra chars that don't belong there
    														  //(which will happen if the badStr is longer than the 
    														  //goodStr),
    			System.out.println("Original Bad String:        " + originalBadStrToChars);
    			System.out.println("Overwritten Bad String:     " + badStrToChars);
    			badStrToChars.subList(goodSize, badStrToChars.size()).clear();//then trim them off the fixed badStr.
    			System.out.println("Trimmed Bad String:         " + badStrToChars);			
    		}
    		
    		System.out.println();
    		
    		//If the badStr is shorter than the goodStr, remember that we already adjusted the badStrToChars size
    		//and put x char place holders in the if statement earlier. Needless to say, we don't need to trim any
    		//chars off of badStrToChars in this case. This print statement verifies that the badStrToChars was
    		//overwritten by goodStrToChars correctly.
    		if(badSmallerThanGood == true) {
    			System.out.println("Original Bad String:        " + originalBadStrToChars + " size = " + originalBadSize);
    			System.out.println("Overwritten Bad String:     " + badStrToChars + " size = " + newBadSize);
    		}
    		//Allow the now overwritten and adjusted badStrToChars ArrayList to become an official string,
    		//so that we can return as a string:
    		StringBuilder str = new StringBuilder();
    		for(char z : badStrToChars) {
    			str.append(z);
    		}
    		String backToStr = String.valueOf(str);
    		return backToStr;//return the overwritten, adjusted, and converted version of the badStr
    	}
    }//end of FixString class
    As it turns out, to fix that bug, I need two for loop statements. One with <=, and another with <
    Java Code:
    for(int i = 0; i <= badStrToChars.size()-1; i++)//line 68
    Java Code:
    for(int i = 0; i < badStrToChars.size()-1; i++)//line 82
    And even though I don't fully understand why, it works!

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,001
    Rep Power
    33

    Default Re: ArrayList ensureCapacity method is not working

    I get this error with the new code:
    Java Code:
            System.out.println("1="+fixBadStrWithArrayList("123", "4"));       
    
    
    
    char at index [0] = 4
    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
    	at java.util.ArrayList.rangeCheck(Unknown Source)
    	at java.util.ArrayList.get(Unknown Source)
    	at FixString1.fixBadStrWithArrayList(FixString1.java:97)
    	at FixString1.main(FixString1.java:13)
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. How to create an ArrayList method?
    By Mostpured in forum New To Java
    Replies: 11
    Last Post: 01-30-2015, 01:10 AM
  2. ArrayList add method
    By cpguy in forum New To Java
    Replies: 11
    Last Post: 10-07-2011, 02:39 AM
  3. ArrayList add method
    By GrahamButcher in forum New To Java
    Replies: 1
    Last Post: 11-01-2010, 11:51 AM
  4. add method from Arraylist - question
    By Adomini in forum New To Java
    Replies: 6
    Last Post: 10-21-2010, 07:08 PM
  5. Calling a method when using an arraylist?
    By Jamison5213 in forum New To Java
    Replies: 10
    Last Post: 01-23-2010, 08:47 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •