java中的数组结构

Array struct in java

本文关键字:结构 数组 java      更新时间:2023-10-16

我正在学习Java,我正在做一些c++代码到Java中,我跟随这个网页http://uva.onlinejudge.org并试图在Java中做一些问题。现在我正在做这个问题http://uva.onlinejudge.org/index.phpoption=com_onlinejudge&Itemid=8&page=show_problem&problem=1072,研究并找出如何在纸上做到这一点后,我发现这个网页的问题似乎很容易遵循:http://tausiq.wordpress.com/2010/04/26/uva-10131/

但是现在,由于我是Java的新手,我想学习如何在Java中做一个结构数组。我现在可以做一个像struct这样的类:如果这是在c++中

struct elephant {
    int weight;
    int iq;
    int index;
} a [1000 + 10];

我可以在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;
        }
    }

但是我不知道如何在c++中把它变成结构体的最后一部分:

a [1000 + 10];

我的意思是,在Java中有一个大象类的对象数组就像在c++中有一个大象元素数组

有没有人能帮助我更好地理解它

Java中对象数组的实现方式与原语数组相同。语法应该是

Elephant[] elephants = new Elephant[1000+10];

这将初始化数组,但不会初始化元素。数组中的任何索引都将返回null,除非您执行以下操作:

elephants[0] = new Elephant();

这应该是你正在寻找的:

Elephant []  array = new Elephant[1010];