Link to home
Start Free TrialLog in
Avatar of AttilaB
AttilaB

asked on

Resizing Arrays based on user input

In the attached short code resizing the String[] array seems to work fine, for some reason the exact same methology with the System.arraycopy() method doesn't work for the int[] array,
and I am clueless how to apply this to to the 2-dimensional int[][] array.

What am I doing wrong with the int[] array and how do you apply the same principle to an
int[][] array?

Thank you for your help.
 
import java.util.Scanner;

public class ResizeArrays {
    
    public static void main(String[] args) {
        
        Scanner inputScan = new Scanner(System.in);
        
        System.out.println("Please enter the number of emloyees:");
        int numberOfEmployees = inputScan.nextInt();
        
        System.out.println("Please enter the number of days worked each week:");
        int  numberOfDaysWorked = inputScan.nextInt();
        
       
        // Arrays will be changed to dynamic arrays according to input values:
        Integer[][] hoursWorkedArray = new Integer[1][1];
        Integer[] totalHoursArray = new Integer[1];
        String[] employeeNamesArray = new String[1];
        
        // change arrays sizes here:
       employeeNamesArray = resizeStringArray(employeeNamesArray, numberOfEmployees);  // WORKING
       totalHoursArray = resizeIntArray(totalHoursArray, numberOfEmployees);   //BAD
       hoursWorkedArray = resizeInt2DArray(hoursWorkedArray, numberOfEmployees, numberOfDaysWorked );  // BAD
       
       
       // Check array sizes:
       System.out.println("employeeNamesArray size: " + employeeNamesArray.length);
       System.out.println("totalHoursArray size: " + totalHoursArray.length);
       System.out.println("hoursWorkedArray sizes: Rows= " + hoursWorkedArray.length + " Columns= " + hoursWorkedArray[0].length);
       
       //   arrayName.length the length attribute returns the number of rows
	   //   arrayName[i].length will return the number of columns in row i	
    }
    
    
    // resize a single-dimensional String [] array:
public static String[] resizeStringArray(String[] arrayToBeResized, int newSize) {
String[] temp = new String[newSize];
System.arraycopy(arrayToBeResized, 0, temp, 0, arrayToBeResized.length);
for(int j = arrayToBeResized.length; j < newSize; j++)
temp[j] = "";
return temp;
}

 
// resize a single-dimensional int[] array:   
public static int[] resizeIntArray(int[] arrayToBeResized, int newSize) {
int[] temp = new int[newSize];
System.arraycopy(arrayToBeResized, 0, temp, 0, arrayToBeResized.length);
for(int j = arrayToBeResized.length; j < newSize; j++)
temp[j] = 0;
return temp;
}

// resize 2-dimensional int[][] array:
private static int[][] resizeInt2DArray(int[][] arrayToBeResized, int newIndex1Size, int newIndex2Size ){
	int[][] temp = new int[newIndex1Size][newIndex2Size];
	
	// ????????????????????????????????????????????
	
	return temp;
}

}

Open in new window

With bad code commented:

Please enter the number of emloyees:
6
Please enter the number of days worked each week:
7
employeeNamesArray size: 6
totalHoursArray size: 1
hoursWorkedArray sizes: Rows= 1 Columns= 1

Process completed.

Open in new window

Avatar of for_yan
for_yan
Flag of United States of America image

Is ther any reason you want to resize?
Why can't you just create array of required size:
int[] totalHoursArray = new int[numberOfEmployees];
int[][] hoursWorkedArray = new int[numberOfEmployees][numberOfDyas];
String [] empoloyeeNames = new String[numberofEmployees];

Open in new window

and youprobnably need int instead of Integer
Avatar of AttilaB
AttilaB

ASKER

In this particular case you are right. Because I could do what you suggested, and just use the variables as I create the arrays, because they are not changed anywhere in the program I posted.

This code I posted was meant to be just a simple example to illustrate my problem however with re-sizing arrays using arraycopy() in general.  In other programs I am working on  I want to keep adding to a set of records saved on disk, and re-load data therefore in other cases the resize cannot be avoided. I just don't want to post too much code to obscure my question, just enough to illustrate my problem.
Can you use ArrayList in all those case where you don't know upfron the final size of the array ?
ArrayLists are much more conveneien and they resize everything for you bbehind the scene and they use
interbnally ArrayCopy and perobably would be more effective that anything we wopuld write our selves
Maybe I'm missing a point here but why don't you just use a for/while loop and copy each element?

When you resize your array, I suggest you double the dimension that is trying to grow past the old boundary.  This approach is more efficient that you might think.  I'd have to dig out my algorithm's textbooks to provide details.  (I remember seeing a proof but don't remember the details.  I'm guessing it's of order log n).
With two dimpnsional array you can have say hashmap. I suggest to use Collections.
I almosst never use arrays, only when there is something completely nonchangeable - say seven days of the week
or something
for_yan still types faster... (how do you do that?)

ArrayList is the approach.  In my algorithm's class, we had to work with ArrayList source instead of using the built in library.

If you are just trying to finish a project, do what for_yan said.  If you are trying to learn, then write your own code.  If you want to learn, you could get Drake's book "Data Structures and Algorithms."  But that book costs over $100 new.  (You could also take a class, that may use that book or some other book as textbook(s)).
I again agree with for_yan, if you are just trying to get the project done using the standard libraries.  Depends on your mission here.  HashMap's are also covered in the book I mentioned.

If you can afford it, perhaps a college class in Data Structures and Algorithms would be a good idea.  (Then you might know as much as for_yan...after a while).
Avatar of CEHJ
>> for some reason the exact same methology with the System.arraycopy() method doesn't work for the int[] array,

Your code works fine, although your for loop is redundant.

For a two dimensional array, it would depend on which dimension you wanted to resize, and were it the dimension indexed second, you could use the single dimension code in a loop.

For your business problem (even though you suggest it's hypothetical) you should avoid any kind of parallel arrays such as in your sample code. The problem then either disappears or is transformed into something quite different
Avatar of AttilaB

ASKER

I thought that since arrays have less overhead they would run much faster for same amount of data
than ArrayLists, given the same (large) amount of data stored.
So in some cases changing array bounds with System.arraycopy() would be preferable
to using ArrayLists, in that case. Am I right?

Example:

If you have an array of objects that would be an array of thousands of instances of a class used to store data would you want to change that to ArrayList too?

ASKER CERTIFIED SOLUTION
Avatar of stachenov
stachenov

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sure, especuially with array of objects I'd switch to arrayList
Overhead is associated right with the same ting - if you start copying arryas uyou'll get rith that overhead
but more.
It is only with the fixed arrays you sometimes can get some economy in time.
And some saving in memory may happne with arrys - but thiose are rare applications when you really care.

So I fiorst do almost everuthing with collections - ther are only sopecial cases where you really want to use arrays
>>1) Resizing int[] array doesn't work because int and Integer are different types

Sorry - i don't understand that - in what what does resizing int[] not work?
>> Sorry - i don't understand that - in what what does resizing int[] not work?

The OP said that "for some reason the exact same methology with the System.arraycopy() method doesn't work for the int[] array", so I explained that it (the methodology) doesn't work because, in the posted code, that array isn't actually an int[] array, but an Integer[] array, which is a different thing.
Well i took int[] literally and was referring to lines 48 to 54 of AttilaB's code
Avatar of AttilaB

ASKER

Thank you for all your comments, they have been very helpful, and  especially for the complete explanation from stachenov.
Well half of it was correct - the half that was an illustration of the following point:

>>
For a two dimensional array, it would depend on which dimension you wanted to resize, and were it the dimension indexed second, you could use the single dimension code in a loop.
>>

As for the first half, as i mentioned, your existing code was fine. Integer[] is also quite possible, e.g.
http://technojeeves.com/joomla/index.php/free/94-resize-a-generic-array