元素周期表的数据结构 [英] Data Structure of the Periodic Table of Elements

查看:225
本文介绍了元素周期表的数据结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是使用元素周期表(或列表)来获取有关Java中特定元素的信息。我想通过原子序数和符号进行搜索(但转换应该很简单)。

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).

我在此JQuery插件。但它存储为JSON文件。

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

硬编码信息似乎最有效(因为它不会经常更改并且由于性能原因),但如何将JSON转换为硬编码的枚举

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 enum?

推荐答案

从:


  • 有关元素的信息是完全静态的

  • 每个元素符号都是字母数字

  • 新元素的发现既罕见又不相关(因为它们非常不稳定)

enum似乎是个不错的选择:

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;
    }
}

这里有一些java功夫值得一个解释。映射放在静态内部(holder)类中,因此在初始化枚举实例之前初始化,这样他们就可以将它们添加到它中。如果不在内部静态类中,则不会进行初始化,因为在枚举类中初始化的第一件事必须是实例,但静态内部类在之前初始化 class已初始化。

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).

这篇关于元素周期表的数据结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆