Java中的C/C++结构类比?

Rav*_*jha -2 c c++ java struct

我在C中有以下代码,而且我对Java知之甚少.

我想知道是否有任何方法可以在Java中创建下面代码中显示的结构.我想我们可以class在Java中使用它,但我在Java Classes中遇到的问题是我无法声明人[10]即这样一个结构的数组.

struct people{
float height;
float weight;
int age;
}people[10];

int main()       // this part of code is just to show how I can access all those elements of struct
{
    int i;
    for(i=0;i<10;i++)
    {
        people[i].height = rand()%7;
        people[i].weight = rand()%80;
        people[i].age = rand()%100;
    }
    for(i=0;i<10;i++)
    {
        printf(" %f %f %d\n",people[i].height,people[i].weight,people[i].age);
    }
return 0;
}
Run Code Online (Sandbox Code Playgroud)

Kha*_*d.K 9

C++中,您可以静态分配对象.

struct People
{
    // struct members are public by default
    float height;
    float weight;
    int age;
}
people[10]; // array of 10 objects

int main ()
{
    // fill some data
    people[0].age = 15;
    people[0].height = 1.60;
    people[0].weight = 65;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是在Java中,你必须动态分配对象,并且创建数组不会分配对象,它只会分配一个引用数组.

package Example;

private class People
{
    // define members as public
    public float height;
    public float weight;
    public int age;
}

class Main
{
    public static main (String [] args)
    {
        // array of 10 references
        People [] p = new People [10];

        // allocate an object to be referenced by each reference in the array
        for (int i=0; i<10; i++)
        {
            p[i] = new People();
        }

        // fill some data
        people[0].age = 15;
        people[0].height = 1.60;
        people[0].weight = 65;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢@Khaled清楚地解释清楚. (2认同)