Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Array Length: How to set an Array's lenght, before I know how long it needs to be?

  1. #1
    Member
    Join Date
    Feb 2011
    Location
    Pittsburgh
    Posts
    62
    My Mood
    Angelic
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Cool Array Length: How to set an Array's lenght, before I know how long it needs to be?

    Dear All:

    I use a method to compare two arrays of type String[]. Any String Value that is not on both arrays I want to be placed in a new array.

    I am not using any cool methods from the API because I am learning, so compare this to a kid with a calculator v a pen and paper.
    (I do use "equals" because I can not work out how not to )

    So in the example I have below I have created the array because I know the answer, there should be one value.
    "String[] newlyLargerPopulation = new String[1];"

    ANSWER I KNOW IS OUT THERE BUT SEEMS LIKE A WASTE AND BAD CODE
    1. Run the method in a dummy run mode.
    2.Record how many String entries will pop up that are not on both lists.
    3.Create the Array now that I know how long it needs to be.
    4.Run the method again and fill the array.

    QUESTION
    How do I get around the need to create the array to capture the values, when I do not know how long the array will need to be to capture all the values.

    OTHER PERTINENT INFORMATION(OPI)
    1. It may be that none of the information in either of the two arrays being compared is the same nor will the length of the arrays always be the same or similar.
    2. I will ad an if statement to make the calculation work to always check the longer array against the shorter array, but this is not important here.


    import java.util.Scanner;
    import java.util.*;
     
    public class ArrayQuestion
    {
     
     
     
    public static String[] overtakenBy(String[] previous, String[] viable)	//Method compares two arrays and returns an array of type string.
    {
    	String[] newlyLargerPopulation = new String[1];                     //The problem, I have to set the arrays length, but in the real world I 
    	                                                                    // will not know what to set the arrays length to.
    		for(int b = 0 ; b < viable.length ; b++)                         // Stepping through the Viable arrays values.
    		{
    			int x = 0;                                   //Counter used to trigger the placement of a String value into the "newlyLargerPopulation" array. 
    			for (int i = 0 ; i < previous.length ; i++)              //Stepping through the previous arrays String Values, checking each one against 
                                                                                     // the viable arrays string value.
    			{
                                    if (viable[b].equals(previous[i]))                                     // Do the values in the respective arrays match?
    					System.out.println(viable[b] + " equals " + previous[i]);      //Place holder to let me see what is going on, not needed by the code. 
    				else
    				{
    					x++;                                                   //If the name did not match then "x" is increased by one, when "x" gets to the same
    					System.out.println("x = " + x);                        // value as previous[].length, this triggers the addition of the String value to the 
    					if ( x == previous.length)                              // array that is returned by the method.
    						{	
    						newlyLargerPopulation[0] = new String(viable[b]);           //value being added to the array that is returned.
     
    						}
    					else;                                                                                          
    				}
    			}
    		}
    	return newlyLargerPopulation;                                                                                      //returning the new array. 
    }
     
     
    public static void main(String[] args)
    {
     
    	String[] previousYear = {"Dog", "Cat", "Rabbit"};                                              //Creating the previousYear array.
     
    	String[] viableSpecies = {"Dog", "Cat", "Rabbit", "Terrapin"};                               //Creating the viableSpecies array.
     
    	String[] theDifference = overtakenBy(previousYear, viableSpecies);                    //Comparing the two and returning an array of type String.
     
    	System.out.println("The name of the species that newly overtook our species by population is the " + theDifference[0]);   //Output for my sake to see that it worked under 
                                                                                                                                      // these controlled conditions.
    }
    }


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Array Length: How to set an Array's lenght, before I know how long it needs to

    The answer is to use an ArrayList.

    You could also create a method that takes an array of length N, and an element to be added to the array, and a method that returns a new array of length N+1 that contains the element.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    Member
    Join Date
    Feb 2011
    Location
    Pittsburgh
    Posts
    62
    My Mood
    Angelic
    Thanks
    15
    Thanked 0 Times in 0 Posts

    Default Re: Array Length: How to set an Array's lenght, before I know how long it needs to

    When you say you can use an ArrayList,

    Are you saying that use an ArryaList in a method that takes an array of length N, and ......

    or are you giving me two separate solutions?

    Assuming you are giving me two different answers.

    In the second answer that does not use ArrayList, are you saying:

    String[] newArray = new String[1]

    newArray = combinerMethod( newArray, additionalElementToBeAddedToArray)

    Thinking about it, this I think I could do. Is this what your answer intended to convey?

    Thanks.

    SpaceMonkey.

  4. #4
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Array Length: How to set an Array's lenght, before I know how long it needs to

    I am not using any cool methods from the API because I am learning
    The API is there to be used. Learn to use it, what the benefits and downsides of different parts of the Java API.

    If it's for a class (or if you just want to learn how Arraylists work), they make a "modest guess" as to what size the array should be. They also use a separate variable to keep track of the number of elements (or size) of the ArrayList is. You can add elements to the ArrayList and that increases the size of the ArrayList but not necessarily the capacity of the implementing array. Whenever the capacity has been reached, create a new array with double the capacity and copy over the old array's data.

    You're original approach is also a valid approach and is sometimes used. However, more often than not the ArrayList approach is used because it's simpler (it may be faster, I honestly have never tried to benchmark it).

  5. #5

    Default Re: Array Length: How to set an Array's lenght, before I know how long it needs to

    If you choose to not use an ArrayList (evne though it is the clearly better choice) because you may not be allowed to, you can always re-define your array.

    //Define array and set length
    String[] stringArray = new String[10];
    int counter = 0;
    while(someBoolean)
    {
    	value = SomeClass.GetNewStringValue();
    	//You have to keep adding to the array while someBoolean is true
    	//create a method that adds the new value to the array
    	addElementToArray(value,counter++,stringArray);
     
    	//re-evaluate the boolean variable
    }
     
    //In the definition of your function
    public String addElementToArray(String value, int size, String array)
    {
    	if(size == array.length)
    	{
    		//new array twice the size of old array
    		String[] tempArray = new String[array.length*2];
    		for(int i=0; i<array.length; i++)
    			tempArray[i] = array[i];
    		//now, redfine array by assigning tempArray to it
    		array = tempArray;
    	}
    	//now you can add the extra element
    	array[size] = value;
    	//it's always good to return elements when they are added
    	return value;
    }
    Kenneth Walter
    Software Developer
    http://kennywalter.com

  6. #6
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Array Length: How to set an Array's lenght, before I know how long it needs to

    Kenneth- Your solution is a bit of a hybrid between mine and helloworld's (better) suggestion. As it is, you're going to have a problem determining where the array indexes actually stop.

    Also, please read this: http://www.javaprogrammingforums.com...n-feeding.html
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  7. #7
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Array Length: How to set an Array's lenght, before I know how long it needs to

    Quote Originally Posted by SPACE MONKEY View Post
    When you say you can use an ArrayList,
    Are you saying that use an ArryaList in a method that takes an array of length N, and ......
    or are you giving me two separate solutions?
    I'm giving you two separate suggestions. As helloworld mentioned, the API is there to be used, and a good programmer knows how to use it. If I were giving a job interview, I might ask how a person would sort an array, and maybe ask for a few lines of code to do so. The person who gives a few different examples of sorting algorithms would definitely be worth a second look, but the person whose answer is Arrays.sort() would probably be a more skilled Java programmer. Ignoring the API is a mistake.

    Quote Originally Posted by SPACE MONKEY View Post
    Assuming you are giving me two different answers.
    In the second answer that does not use ArrayList, are you saying:
    String[] newArray = new String[1]
    newArray = combinerMethod( newArray, additionalElementToBeAddedToArray)
    Thinking about it, this I think I could do. Is this what your answer intended to convey?
    Almost. But why would your array only have one index? And helloworld's suggestion on creating a class that contains an array and keeps track of things like how many elements are in it (which usually will be smaller than the array's actual size) is probably the way to go. You're basically re-implementing ArrayList, but if your goal is to learn, that's the way to go.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

Similar Threads

  1. java program with array's....need help!!
    By magictricks1020 in forum Collections and Generics
    Replies: 1
    Last Post: May 2nd, 2011, 11:08 PM
  2. max length of an array?
    By qsbladey in forum Collections and Generics
    Replies: 4
    Last Post: April 3rd, 2011, 11:17 AM
  3. Getting length of individual token?
    By Kimimaru in forum What's Wrong With My Code?
    Replies: 10
    Last Post: February 10th, 2011, 02:48 AM
  4. Finding the length of a two dimensional array
    By petemyster in forum Java Theory & Questions
    Replies: 2
    Last Post: December 12th, 2010, 10:21 PM
  5. Run Length Encoding Problem
    By Scottj996 in forum File I/O & Other I/O Streams
    Replies: 0
    Last Post: January 7th, 2010, 07:24 AM

Tags for this Thread