Creating an array of objects

I have a class called ElementInfo

public class ElementInfo {

    public String name;
    public String symbol;
    public double mass;

}

Then I attempt to create an array of ElementInfo like so:

ElementInfo e[] = new ElementInfo[2];

e[0].symbol = "H";
e[0].name = "Hydrogen";
e[0].mass = 1.008;

//...

Dont tell me i have to call new for every instance of the class!

Can I do this:

ElementInfo e[] = new ElementInfo[100];
for(ElementInfo element: e){
    e = new ElementInfo();
}

Answers


You have to call new for every element of the class.

public class ElementInfo {

    private String name;
    private String symbol;
    private double mass;

    public String get_name() { return name; }
    public String get_symbol() { return symbol; }
    public double get_mass() { return mass; }

    public ElementInfo(name, symbol, mass) {
        this.name = name;
        this.symbol = symbol;
        this.mass = mass;
    }
}

Then create them like so:

e[0] = new ElementInfo("H", "Hydrogen", 1.008);

Dont tell me i have to call NEW for every instance of the class!

Exactly.

You just created an array of nulls.


You have to create a new instance for each element, but it's not hard :

ElementInfo e[] = new ElementInfo[2];
for (int i = 0; i < e.length; i++)
    e[i] = new ElementInfo();

ElementInfo e[] = new ElementInfo[2];

e[0] = new ElementInfo();
e[0].symbol = 'H'; ...

Need Your Help

Using Multibox (mootools) on an IBM WebSphere Portal 6.1 Portlet

mootools portlet websphere-portal multibox

I'm trying to deploy a portlet in IBM WebSphere Portal 6.1, that features a MultiBox (an extended version of a Lightbox, which not only allows to display pictures, but also other kind of components...

Encrypting SQLite

sqlite

I am going to write my own encryption, but would like to discuss some internals. Should be employed on several mobile platforms - iOS, Android, WP7 with desktop serving more or less as a test platf...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.