加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java可选问题,我这样做了吗?

发布时间:2020-12-15 04:23:49 所属栏目:Java 来源:网络整理
导读:我有一种“不良习惯”,即将零点抛到某些地方,例如当某些东西不存在时的枚举器. 例: private enum Foo { NULL(1,null,2),NOT_NULL(3,new Bar(),4); private int a,c; private Bar b; Foo(int a,Bar b,int c) { this.a = a; this.b = b; this.c = c; }} 所以
我有一种“不良习惯”,即将零点抛到某些地方,例如当某些东西不存在时的枚举器.

例:

private enum Foo {
    NULL(1,null,2),NOT_NULL(3,new Bar(),4);

    private int a,c;
    private Bar b;

    Foo(int a,Bar b,int c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }
}

所以现在我正在尝试将我的代码转换为使用Optional< T>像每个人都在暗示,但我不确定我是否正确地做到了.

这是我的代码(Trimmed枚举):

public static enum Difficulty { 
    EASY,MEDIUM,HARD
}

public static enum SlayerTasks {
    NONE(0,Optional.empty(),Optional.empty()),NPC(1,Optional.of(Difficulty.EASY),Optional.of("That one place."),Optional.of(1));

    private int taskId;
    private Optional<Difficulty> difficulty;
    private Optional<String> location;
    private Optional<Integer> npcId;

    SlayerTasks(int taskId,Optional<Difficulty> difficulty,Optional<String> location,Optional<Integer> npcId) {
        this.taskId = taskId;
        this.difficulty = difficulty;
        this.location = location;
        this.npcId = npcId;
    }

    public int getTaskId() {
        return taskId;
    }

    public Difficulty getDifficulty() {
        return difficulty.get();
    }

    public String getLocation() {
        return location.get();
    }

    public int getNpcId() {
        return npcId.get();
    }
}

困扰我的是指向#get()的文档找到here,其中指出:

If a value is present in this Optional,returns the value,otherwise throws NoSuchElementException.

所以,我认为为了防止这种情况,我会将getter包装在#isPresent()中,但后来我无法弄清楚如何返回空.

这是正确的做事方式,还是我错过了什么?我不是在寻找“修复”,我正在寻找有关效率和正确实践的信息.

解决方法

如果没有什么可以归还的话,你需要问问自己你想让你的吸气者做什么.

实际上只有四种选择:

>返回null(但是你会回到你想要避免的那个);
>让你的getter返回一个Optional< T>而不是T;
>如果没有设置,则返回默认值;
>抛出异常.

除非对默认应该是什么有非常明确的正确答案,否则我会选择2. 4只有在客户端代码应该始终知道是否存在某些东西时才适用,并且只有在需要时才会询问(这是不寻常的,但并非不可能).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读