Reputation: 25
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"
Upvotes: 3
Views: 8178
Reputation: 1
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());
Upvotes: 0
Reputation: 33544
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
}
Upvotes: 2
Reputation: 15052
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);
Upvotes: 7
Reputation: 178521
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.
Upvotes: 3