Solved

Resizing Arrays based on user input

Posted on 2011-09-19
17
494 Views
Last Modified: 2012-05-12
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
Comment
Question by:AttilaB
  • 5
  • 4
  • 3
  • +2
17 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 36561261
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
 

Author Comment

by:AttilaB
ID: 36561414
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36561491
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
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 36561505
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36561521
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
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 36561524
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
 
LVL 13

Expert Comment

by:Hugh McCurdy
ID: 36561534
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 36561539
>> 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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

Author Comment

by:AttilaB
ID: 36561554
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
 
LVL 4

Accepted Solution

by:
stachenov earned 500 total points
ID: 36561593
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
 
LVL 47

Expert Comment

by:for_yan
ID: 36561612
Sure, especuially with array of objects I'd switch to arrayList
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36561625
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 36561800
>>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
 
LVL 4

Expert Comment

by:stachenov
ID: 36561825
>> 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
 
LVL 86

Expert Comment

by:CEHJ
ID: 36561893
Well i took int[] literally and was referring to lines 48 to 54 of AttilaB's code
0
 

Author Closing Comment

by:AttilaB
ID: 36562463
Thank you for all your comments, they have been very helpful, and  especially for the complete explanation from stachenov.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 36563750
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

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

Join & Write a Comment

I use more than 1 computer in my office for various reasons. Multiple keyboards and mice take up more than just extra space, they make working a little more complicated. Using one mouse and keyboard for all of my computers makes life easier. This co…
Let’s list some of the technologies that enable smooth teleworking. 
This video teaches viewers about errors in exception handling.
The viewer will learn how to successfully download and install the SARDU utility on Windows 7, without downloading adware.

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now