I can't figure how to get this going, for every object I create I want to add that to the existing array. I read about arraycopy but I don't know how to increase the existing size of the array and always end up with array out of index error...

A a1 = new A(1, 2, "test");

size = 1;
sizeCounter = 1;
A a[] = new A[size];
a[0] = a1;

A a2 = new A(3, 4, "test2");

sizeCounter++;
if (sizeCounter>=size){
size++;}

A[size-1] = a2;
Member Avatar for iamthwee

Why not encompass your existing class around the ArrayList. Then just access the .add() method?

iamthwee is right, you should be using ArrayList. You cannot increase the size of an existing array. You have to create a new array that is one larger than the current array, then you can use System.arraycopy to copy the existing elements from the old to the new array, than add the new element.

Doh! Ok, then, I'll just increase the size of the array. I was doing somethig similar to below, everything is done but I thought it would be neat idea to increase the array dynamically.

prompt user for input
checkinput()
if no dupe add to array
else error msg

Member Avatar for iamthwee

Doh! Ok, then, I'll just increase the size of the array. I was doing somethig similar to below, everything is done but I thought it would be neat idea to increase the array dynamically.

prompt user for input
checkinput()
if no dupe add to array
else error msg

You obviously missed my post then...

Guys you can use

import java.util.List;

List <String> wordset = new ArrayList <String>();

usimg this you can get dynamic arrays working well... :)

Member Avatar for harsh2327

You could even use Vector class.
Its implementation is much simpler.
Its in java.util package

Doh! Ok, then, I'll just increase the size of the array. I was doing somethig similar to below, everything is done but I thought it would be neat idea to increase the array dynamically.

prompt user for input
checkinput()
if no dupe add to array
else error msg

you need to know that the array that you use in java is not flexible to increase the size of the array by itself, the array is a STATIC data structure.

if you make

int [] arr = new int[10];

this array will remain in your scope of length 10, unless you make a new array that is nor related to that one and of bigger size and then put the elements of the first array in the second array and then make the first array point to the second array.

int [] arr = new int[10];
/* put data in the 10 elements of arr
-----
----
*/
int []arr2 = new int[arr.length * 2];
//copy the elements of arr to the first 10 elements of arr2
arr = arr2;

or you can easily use arrayList as they told you, which already does that.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.