Domenico Liccardo Domenico Liccardo - 6 months ago 18
Objective-C Question

Structured array in Java

I am trying to migrate my Objective C code into Java to learn this programming language.

I would like to "convert" the following ObjectiveC structure into Java, but I couldn't find the equivalent Java structure:

g_vo2MaxFemales = @[
@{
@"fromAge": @(13),
@"tillAge": @(19),
@"beginner": @(29.95),
@"regular": @(36.95),
@"pro": @(40.5)
},
@{
@"fromAge": @(20),
@"tillAge": @(29),
@"beginner": @(28.25),
@"regular": @(35),
@"pro": @(39)
}
...
];


Which is the similar Java "object"?

Answer

It is easy if you have YourClass class and the constructor with all instance fields. Just create an array of YourClass.

YourClass[] array = {
    new YourClass(13, 19, 29.95, 36.95, 40.5),
    new YourClass(...),
    ...
};

The class will look like

class YourClass {
    private int fromAge;
    private int tillAge;
    private double beginner;
    private double regular;
    private double pro;

    public YourClass(int fromAge, int tillAge, double beginner, double regular, double pro) {
         this.fromAge = fromAge;
         this.tillAge = tillAge;
         this.beginner = beginner;
         this.regular = regular;
         this.pro = pro;
    }
 }

The names of the fields are not pretty, I've used OP's names for his understanding.


With Project Lombok you could write @AllArgsConstructor annotation above the class and not write this massive constructor. It will be generated at the compile stage for you.

Comments