Reputation: 933
I am learning Java and I am doing some C++ codes into java, I am following this webpage http://uva.onlinejudge.org and trying to do some of the problems in Java. Now I am doing this problem http://uva.onlinejudge.org/index.phpoption=com_onlinejudge&Itemid=8&page=show_problem&problem=1072 and after researching and figure out how to do it on paper I found this webpage where the problems seems easy to follow: http://tausiq.wordpress.com/2010/04/26/uva-10131/
But now, and due to the fact I am new on Java, I want to learn how to do an array of struct in Java. I now I can do a class like a struct: if this is in C++
struct elephant {
int weight;
int iq;
int index;
} a [1000 + 10];
I can do this in Java:
public class Elephant {
private int _weight;
private int _iq;
private int _index;
public Elephant(int weight, int iq, int index) {
this._weight = weight;
this._iq = iq;
this._index = index;
}
public int getWeight() {
return this._weight;
}
public int getIQ() {
return this._iq;
}
public int getIndex() {
return this._index;
}
public void setWeigth(int w) {
this._weight = w;
}
public void setIQ(int iq) {
this._iq = iq;
}
public void setIndex(int i) {
this._iq = i;
}
}
But I don't know how I can turn this into the last part of the struct in c++:
a [1000 + 10];
I mean, having an array of a objects of the class Elephant in Java like having an array of elements elephants in c++
Could someone help me to understand it better..
Upvotes: 1
Views: 8121
Reputation: 35598
Arrays of objects in Java are accomplished the same way as an array of primitives. The syntax for this would be
Elephant[] elephants = new Elephant[1000+10];
This will initialize the array, but it will not initialize the elements. Any index into the array will return null until you do something like:
elephants[0] = new Elephant();
Upvotes: 5
Reputation: 69440
This should be what you are loking for :
Elephant [] array = new Elephant[1010];
Upvotes: 1