简体   繁体   English

java关联数组之类的东西不止一种数据类型

[英]java associative array sort of thing with more than one data type

imagine this: DataTypeForConfigs config with String keys, but values of either String , Integer , or Boolean , in Java, JSON can do that, but I'm making a format That goes along the lines of:想象一下: DataTypeForConfigs config带有String键,但是StringIntegerBoolean ,在 Java 中,JSON 可以做到这一点,但我正在制作一种格式,该格式如下:

number "coolness" is 9001 means int coolness = 9001; number "coolness" is 9001表示int coolness = 9001;

It's method is: Read line, read each word, think what to make of it, set it to a Variable within it's reach它的方法是:阅读一行,阅读每个单词,思考如何制作它,将其设置为一个可以访问的变量

Also: what would happen if another thing had its own place to put config?另外:如果另一个东西有自己的放置配置的地方会发生什么? a null would be read?会读取空值吗? WHY?为什么? constructor thinks a file has null on it?构造函数认为文件上有空值? Rage face.愤怒的脸。

Say... should I make a class called SettingVal that when given a getValue() call it would say what it is?说...我应该创建一个名为SettingVal的类,当给定getValue()调用时,它会说出它是什么吗?

SO:所以:

config["Coolness"].getValue();

return 's 9001 return 9001

WAIT:等待:

How on earth would I make the getValue() method?我到底如何制作getValue()方法? HOW?如何? RETURN VALUE WONT LIKE THIS!!返回值不会这样!! OH CRAP!哦,废话!

Solution:解决方案:

Another Data type comes in and checks its 'gender' ( String , Bool , Int ) and then checks it's value of that 'gender' ( strVal , boolVar , intVar )另一种数据类型进来并检查其“性别”( StringBoolInt ),然后检查它的“性别”值( strValboolVarintVar

Return values are a big problem when dealing with this.处理这个时,返回值是一个大问题。 I need a stress free version , so maybe I can have a void returning method that runs another method based on what data type it is said to hold!我需要一个无压力版本,所以也许我可以有一个void返回方法,该方法根据据说保存的数据类型运行另一种方法! Am I right?我对吗?

I have a temporary solution, setVar works, getVar is get*Var , where * is Str , Bool or Int .我有一个临时解决方案, setVar有效, getVarget*Var ,其中 * 是StrBoolInt

Sadly, I Haven't yet been able to properly read it from a file, the method I made to read from a file is not working.可悲的是,我还没有能够从文件中正确读取它,我从文件中读取的方法不起作用。 It makes a Map<String,SettingVar> , using a HashMap constructor and returns that map, but seems whenever I try to access a variable from it that variable is null .它使用HashMap构造函数生成Map<String,SettingVar>并返回该映射,但似乎每当我尝试从中访问变量时,该变量为null It is probably because of IOException s and FileNotFoundException s, FileNotFound ?这可能是因为IOException s 和FileNotFoundException s, FileNotFound Why?为什么? It Shouldn't be running until called.在被调用之前它不应该运行。 Oh, and also NullPointerException s Please Help!哦,还有NullPointerException s 请帮忙!

SUBQUESTION: what happens when you MapVariable.put({NAME HERE}, varToPutIn) many times in a for loop?子问题:当您在 for 循环中多次使用MapVariable.put({NAME HERE}, varToPutIn)时会发生什么? what about MapVariable.put({NAME HERE},new ...) ? MapVariable.put({NAME HERE},new ...)怎么样?

My code in links:我在链接中的代码:

https://gist.github.com/anonymous/66c4d1c2d2718a4cc9b9 https://gist.github.com/anonymous/66c4d1c2d2718a4cc9b9

because I don't have enough reputation因为我没有足够的声望

PS: OK! PS:好的! ive made the config reader work now, and SettingVar , and SettingContainer and im working on ConfigWriter which is good, now working on a prototype for a java command prompt like thing, and soon a WHOLE OS!!我现在让配置阅读器工作,并且SettingVarSettingContainer和我在ConfigWriter上工作,这很好,现在正在开发一个类似 java 命令提示符的原型,很快就会有一个完整的操作系统! wait... java is an os.等等... java 是一个操作系统。 thats why java virtual machine... oh.这就是为什么java虚拟机...哦。 Well, how can I close this question and turn the outcome into a revolutionary new thingy for kids who want to learn to code java *cough cough* especialy ones with higher learning ability than social ability... and like to hang around with mature people who dont bully them like all the kids in their school.好吧,我该如何结束这个问题并将结果变成一个革命性的新事物,对于想要学习 Java 代码的孩子*咳咳* 尤其是那些学习能力高于社交能力的孩子......并且喜欢和成熟的人呆在一起谁不像学校里的所有孩子那样欺负他们。 (Wow, that was specific) (哇,那是具体的)

I would use a Plain Old Java Object which you can read from JSON.我会使用一个普通的旧 Java 对象,你可以从 JSON 中读取它。

class Config {
    int coolness = 9001;
    String hello = "world";
    boolean cool = true;
}

This way you can have fields with a variety of types.通过这种方式,您可以拥有各种类型的字段。

The type you're looking for is Map<String,Object> , but it is not type-safe and you'll have to do a bunch of casting:您正在寻找的类型是Map<String,Object> ,但它不是类型安全的,您必须进行大量转换:

Map<String,Object> config = new HashMap<>();
config.put("coolness",9001);
config.put("hello","world");
config.put("cool", true);

boolean cool     = (Boolean) config.get("cool");
String  hello    = (String)  config.get("world");
int     coolness = (Integer) config.get("coolness");

Generally, I'd recommend creating a dedicated class for holding your configuration (each field = one property), which is strongly typed and doesn't require casting, and then use something like Jackson to serialize/deserialize it from json, yaml, or xml.通常,我建议创建一个专用类来保存您的配置(每个字段 = 一个属性),它是强类型的并且不需要强制转换,然后使用 Jackson 之类的东西从 json、yaml 或xml。

This provides structure to your configuration, and will cause any issues with malformed configurations to show up when you start your application/load your configuration, and not in the middle of your application.这为您的配置提供了结构,并且会导致在您启动应用程序/加载配置时出现任何格式错误的配置问题,而不是在应用程序中间显示。

SUBQUESTION: what happens when you MapVariable.put(varToPutIn) many times in a for loop?子问题:当您在 for 循环中多次使用MapVariable.put(varToPutIn)时会发生什么?

A Map represents a mapping. Map 代表一个映射。 If you do this:如果你这样做:

Map<String, Object> map = new HashMap<>();
for (int i = 0; i < 10; i++) {
    map.put("myKey", Integer.valueOf(i));
}

what happens is that you add a mapping from "myKey" to zero, then update it to one, two, three and so on.发生的情况是您添加从“myKey”到零的映射,然后将其更新为一、二、三等。 When the loop ends, "myKey" will map to nine.当循环结束时,“myKey”将映射到九。

In short, the map entry for "myKey" is behaving like a variable of type Integer that you assign to repeatedly.简而言之,“myKey”的映射条目的行为就像您重复分配的Integer类型的变量。

I'm afraid your Gists are telling me that you simply didn't take on board what @Darth Android wrote.恐怕您的要点告诉我您根本没有接受@Darth Android 所写的内容。 Rather that hashing through your code, here's a simple way to parse your config file syntax (more or less) and load it into a Map<String, Object>而不是通过您的代码散列,这里有一个简单的方法来解析您的配置文件语法(或多或少)并将其加载到Map<String, Object>

Note: I have not compiled or tested this code.注意:我没有编译或测试过这段代码。 It is written to be read and understood, rather than borrowed.它是用来阅读和理解的,而不是借来的。

Map<String,Object> config = new HashMap<>();
try (Scanner s = new Scanner(new FileReader(someFile))) {
    while (s.hasNext()) {

        // Syntax is '<type> <name> is <value>'

        String[] words = s.nextLine().split("\\s+");
        if (words.length != 4 || !words[2].equals("is")) {
            throw MySyntaxException("unrecognizable config");
        }
        String type = words[0];
        String name = words[1];
        String val = words[3];
        switch (type) {
        case "number":
            map.put(name,  Integer.valueOf(val));
            break;
        case "boolean":
            map.put(name,  Boolean.valueOf(val));
            break;
        case "string":
            map.put(name, val);
            break;
        default:
            throw MySyntaxException("unknown type");
        }
    } catch (NumberFormatException ex) {
        throw MySyntaxException("invalid number");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM