View Full Version : java: arraylist question.

01-25-2005, 05:17 AM
ok this maybe a trivial question but its been buggin me for 2 hours now. So the problem goes as follows:

I have an array of some size which contains random numbers generated by the comp. between 1 to 100.

lets say the array is size 5 with the output which looks like so:

0 25
1 1

Problem 1). Upon checkin that this array is full, i call upon a function named increaseSize which basically doubles up the length of the array (to add more data).

so instead of array size 5, we get the same array but size 10.

public void increaseSize() {

int[] temp= new int[list.length * 2 ];

for (int j=0; j < list.length; j++) {
temp[j]= list [j];



now this seems to look ok. So we then go to problem #2;

I'm required to prompt a user to enter a value that would be added to this array. Lets say, i wanna add # 14 to the array

so the desired output should be:

0 25
1 1
2 14

my code looks as follows:

public void addElement(int newVal) {

//count is declared in used in the function that fills that array w/ the random //numbers, I used it in a way to keep track of what the current number of //elements are.

if (count==list.length)

for (int i=0; i<list.length; i++)

//i'm kinda stuck here. I had some old code before, but didn't work at all!!

For some reason, my output would show up the index 0 i.e., 0 25 ok
but after that...all the outputs become 0 as well, and then index 2 becomes 14. I think there's something fishy with my code for increaseSize but i cannot seem to debug it.

problem # 3:

This one asks for the user to enter a number after i print up array list to be remove and also shifting up or filling up that hole w/ the array element next to it.

so lets say i wanna remove the value 1 from the array list in the previous question.

the desired output should be:

0 25
1 14
2 0

I tried two versions of how to do it. I understand that concept that i gotta somehow implement an if statement in the for loop to check the value appearing at the first instant and then replacing it with the array element next to it. These two versions somehow are still not giving me any hope to finishing up this java homework.

public void removeFirst(int newVal)

int found=0;

//for(int i=0; i<list.length; i++)
// {
// while ((found!=1)&&(list[i]==newVal))
// {
// list[i]=list[i+1];
// i=i-1;
// found=1;

// }

// }

int i;
int j;


while ((i+j) < list.length)


At this point i'm just resting my brain and hoping that someone may enlighten me with this mess that i'm in. Thanks in advance.

And if you want to see the menu output thing..it should look like this: