I have a set of three numbers and I want to store multiple copies of this set in an array. for example, If I was doing it in C it would be something like:
struct tParams
{
int v;
double A;
double n;
};
static struct tParams Params[] =
{
{ 4230, 1.477404177730177e-04, 1.9565},
{ 3680, 1.920339268755614e-04, 1.925 },
{ 3450, 2.894751026819746e-04, 1.875 },
{ 3295, 4.349905111115636e-04, 1.825 },
//...
};
How would I go about this in Java?
Thanks
EDIT To clarify, these values will be hard coded and only referenced. If I use a ListArray of classes, it looks like I need to add each object from within a method.
I'm building a class with methods that preform mathematical operations. Some of these methods use the data I am hard coding to get coefficients. In C, the structs are defined within the main mathOperations class, but not in a method.
Depends on just what you're trying to do.
In general, you probably want to use a class in Java where you would have used a struct in c. Something like this would be the most standard way to do it:
public class Params {
private Integer v;
private Double a;
private Double n;
public Params(int V, double A, double N){
this.v=V;
this.a=A;
this.n=N;
}
public Integer getV() {
return v;
}
public void setV(Integer v) {
this.v = v;
}
public Double getA() {
return a;
}
public void setA(Double a) {
this.a = a;
}
public Double getN() {
return n;
}
public void setN(Double n) {
this.n = n;
}
}
The short variable names are generally considered poor practice in Javaland for variables with class scope. While it would be possible to do this without the getters and setters by just making the class variables public, that's generally (though by no means universally), considered poor practice as well. For a simple class like this with no behavior, I'd probably just make everything public.
I think this is the most literal translation of your C code:
class tParam {
int v;
double A;
double n;
private tParam(int v, double A, double n) {
this.v = v;
this.A = A;
this.n = n;
}
}
tParam[] params = {
new tParam(4230, 1.477404177730177e-04, 1.9565),
new tParam(3680, 1.920339268755614e-04, 1.925),
new tParam(3450, 2.894751026819746e-04, 1.875),
new tParam(3295, 4.349905111115636e-04, 1.825)
};
It has the advantage of not using all those setters which are redundant for your case since they're 'set once' as you say. Also, given that the data is a static list, there's no point using a List class - the array is fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With