felixd felixd - 24 days ago 5x
Java Question

Data Structure of the Periodic Table of Elements

My goal is to use the periodic table of elements (or a list) to get information about a specific element in Java. I want to search it by atomic number and symbol (but that conversion should be simple).

I found that information in this JQuery plugin. But it is stored as a JSON file.

It seems like it would be most efficient to hardcode the information (since it doesn't change too often and due to performance reasons), but how do I convert JSON to a hardcoded




  • the information about elements is totally static
  • each elemental symbol is alphanumeric
  • the discovery of new elements is both rare and irrelevant (because they are extremely unstable)

An enum seems a good option:

public enum Element {
    H(1, "Hydrogen", 1.008, -259.1),
    He(2, "Helium", 4.003, -272.2),
    Li(3, "Lithium", 6.941, 180.5),
    // ... 90+ others

    private static class Holder {
        static Map<Integer, Element> map = new HashMap<Integer, Element>();

    private final int atomicNumber;
    private final String fullName;
    private final double atomicMass;
    private final double meltingPoint;

    private Element(int atomicNumber, String fullName, double atomicMass, double meltingPoint) {
        this.atomicNumber = atomicNumber;
        this.fullName = fullName;
        this.atomicMass = atomicMass;
        this.meltingPoint = meltingPoint;
        Holder.map.put(atomicNumber, this);

    public static Element forAtomicNumber(int atomicNumber) {
        return Holder.map.get(atomicNumber);

    public int getAtomicNumber() {
        return atomicNumber;

    public String getFullName() {
        return fullName;

    public double getAtomicMass() {
        return atomicMass;

    public double getMeltingPoint() {
        return meltingPoint;

There's a bit of java kung fu going on here that deserves an explanation. The map is put inside a static inner (holder) class so it gets initialized before the enum instances are initialized, that way they can add themselves to it. If not in the inner static class, it would not be initialize, because the first thing initialized in the enum class must be the instances, but static inner classes are initialized before the class is initialized.

This approach means the the instances don't need to be listed in any particular order (they could be alphabetical listed, or otherwise).