I have a class in Java which has 2 fields like
Class A
{
int i;
double v;
}
I make an array of object of class A like:
A[] x = new A[3];
After assigning the memory to object I assign value to object like:
A[0].i = 1;
A[0].v = 2.5;
A[1].i = 2;
A[1].v = 3.5;
A[2].i = 55;
A[2].v = 1.5;
I was wondering it there was a better way to initialize the object-values.
public class A {
int i;
double v;
public A(int ii, double dd) {
i = ii;
v = dd;
}
public static void main(String[] args) {
A[] a = new A[10]; // size
for (int i = 0; i < a.length; i++) {
a[i] = new A(1, 1.0);
}
}
}
You can also fill elements by this way:
A[] a = new A[] { new A(1, 2.5), new A(2, 3.5), new A(55, 1.5) };
Yes: use constructors :
A[] x = new A[]{new A(1, 2.5), ... };
Update: wrt. to comment below:
// Fake constructor
public static A new_A(int i, double v) {
A x = new A();
x.i = i;
x.v = v;
return x;
}
A[] x = new A[]{new_A(1, 2.5), ... };
Class A
{
private int i;
private double v;
void setI(int i){
this.i =i;
}
void setV(double v){
this.v =v;
}
}
After that assign values like A[0].setI(1);Also provide getters for the variables.
Go for setters\\getters and a constructor.
class A {
int i;
double v;
public A(int i, double v) {
super();
this.i = i;
this.v = v;
}
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
public double getV() {
return v;
}
public void setV(double v) {
this.v = v;
}
}
And if you init it with those 3 values you might as well do:
A[] x = {new A(1,2.5), new A(2, 3.5), new A(55,1.5)};
Modify ur code as follows
Class A
{
private int i;
private double v;
public A(int x,double y)
{
i=x;
v=y;
}
}
class mainclass{
public static void Main(String []args)
{
A[] x = new A[3];
double i=1,v=2.5;
for(int i=0;i<2;i++)
{
x[i]=new A(i,v);
i+=1;
v+=1.0;
}
x[3]=new A(55,1.5);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.