Hi, I'm a senior in high school taking a java class as an elective. I'm having a lot of fun learning, but recently I have come across a problem. While learning about arrays I noticed that unlike javascript in java you can't change to length of arrays after they have been initialized. I tried to write a class that I could use to lengthen arrays, but I am having a little trouble, and my teacher can't seem to find my problem. I'm going to post what I have written so far, using bluejay, and if you could point out my mistake I would be greatly appreciative.
The example class is a driver that should show how the arrayadjust class changes the length of the array.
public class example
{
public static void main(String[]args)
{
arrayadjust arrayadjuster = new arrayadjust();
int[] array = new int[10];
arrayadjuster.adjustint(array,15);
System.out.println(array.length);
}
}
The arrayadjust class uses the copyarray class.
public class arrayadjust
{
void adjustint(int[] array, int newlength)
{
copyarray arraycopier = new copyarray();
int oldlength = array.length;
int[] temparray = new int[oldlength];
arraycopier.copyiray(array,temparray);
array = null;
array = new int[newlength];
arraycopier.copyiray(temparray,array);
}
}
This class just copies one array onto another, I'm fairly certain that it works as it should.
public class copyarray
{
void copyiray(int[] array1, int[] array2)
{
for(int i = 0; i<array2.length && i<array1.length; i++)
{
array2[i] = array1[i];
}
}
void copydray(double[] array1, double[] array2)
{
for(int i = 0; i<array2.length && i<array1.length; i++)
{
array2[i] = array1[i];
}
}
void copysray(String[] array1, String[] array2)
{
for(int i = 0; i<array2.length && i<array1.length; i++)
{
array2[i] = array1[i];
}
}
void copycray(char[] array1, char[] array2)
{
for(int i = 0; i<array2.length && i<array1.length; i++)
{
array2[i] = array1[i];
}
}
}
I hope this isn't too overwhelming of a problem to post here. I also hope there isn't some incredibly simple answer that will make it seem as if I am wasting your time. I think my problem has something to do with how arrays are passed, whether they are passed as aliases or not, or something like that, but I'm not sure.
P.S. When I run this I do not get an error message, but the array doesn't get changed.


