3

I am pretty new to java.

I want to have an array of a class whose length may vary during run time

code:

class Num
{
  ......
  ......
}

if Num is my class , how will i create new instances. My current code is pretty similar to:

Num n[ ];
int length=0;
.
.
.
n[length++]=new Num();  

from this code I'm getting error :

"Uncompilable source code - variable factors might not have been initialized"
1
  • 4
    Just a heads-up—I don't think that error you're getting at the bottom has anything to do with your array creation syntax. Do you have a variable named factors declared but not initialized? Commented Aug 19, 2012 at 14:33

4 Answers 4

7

You can use an ArrayList for this purpose.

ArrayList<Num> myListOfNum = new ArrayList<Num>();

and then keep adding the objects of Num as and when required.

Num num1 = new Num();
myListOfNum.add(num1);
Num num2 = new Num();
myListOfNum.add(num2);

EDIT:

And to access you can use the get() method along with the specific index.

Num tempNum = myListOfNum.get(indexGoesHere);
Sign up to request clarification or add additional context in comments.

2 Comments

how can i acces each element from ArrayList??
@sebastian-thomas List supports both serial access (using iterator or listIterator) as well as random access (using get, set, add, etc.)
3

You need to first create the array itself, before you are trying to set the elements in it.

 Num[] n = new Num[SIZE];

Note that Num n[]; is just declaring a variable of type Num[] with the identifier n.

Note however, that in java - arrays are of fixed lengths. If you are looking for a variable length array, an array is probably not what you need. @KazekageGaara suggested an alternative - for this purpose.

1 Comment

i am nt sure of size..it may vary during run time
2

Use the Java Collection

List will be good if sequence is more important.

Set if uniqueness is important

Map when key-value pair is important

List<MyClass> arrList = new ArrayList<MyClass>();

arrList.add(mobj1);
arrList.add(mobj2);
arrList.add(mobj3);

for(MyClass m : arrList){

      // m is the Values of arrList stored in

 }

Comments

0

The simple way to do this is by using ArrayList

ArrayList<Num> numList = new ArrayList<>();
    // Add elements to the ArrayList
    numList.add(new Num());
    numList.add(new Num());

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.