Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 520
  • Last Modified:

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

0
AttilaB
Asked:
AttilaB
  • 5
  • 4
  • 3
  • +2
1 Solution
 
for_yanCommented:
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
0
 
AttilaBAuthor Commented:
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.
0
 
for_yanCommented:
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
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
Hugh McCurdyCommented:
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).
0
 
for_yanCommented:
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
0
 
Hugh McCurdyCommented:
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)).
0
 
Hugh McCurdyCommented:
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).
0
 
CEHJCommented:
>> 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
0
 
AttilaBAuthor Commented:
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?

0
 
stachenovCommented:
1) Resizing int[] array doesn't work because int and Integer are different types (int is just a 32-bit integer, and Integer is an Object storing an int inside). They are somewhat interchangeable, but not everywhere (for example, null is a valid value for Integer, but not a valid value for int). Just replace int with Integer everywhere, or Integer with int, and it'll work.

2) For two-dimensional arrays, there is no such thing in Java, actually. Just like C/C++, a two-dimensional array is just an array of arrays (and not all of them need to have the same size, by the way). So you just do the same thing with every array, something like this:

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

        for (int i = 0; i < arrayToBeResized.length; i++) {
            final int[] arrayI = arrayToBeResized[i];
            System.arraycopy(arrayI, 0, temp[i], 0, arrayI.length);
        }
	
	return temp;
    }

Open in new window


0) You don't need to explicitly set int elements to zero. All primitive-type (int included) arrays are initialized to zeroes on allocation, and reference types initialized to null (Integer included).
0
 
for_yanCommented:
Sure, especuially with array of objects I'd switch to arrayList
0
 
for_yanCommented:
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
0
 
CEHJCommented:
>>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?
0
 
stachenovCommented:
>> 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.
0
 
CEHJCommented:
Well i took int[] literally and was referring to lines 48 to 54 of AttilaB's code
0
 
AttilaBAuthor Commented:
Thank you for all your comments, they have been very helpful, and  especially for the complete explanation from stachenov.
0
 
CEHJCommented:
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
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 5
  • 4
  • 3
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now