具有非最终成员的不可变Java类 [英] Immutable Java class with non-final member

查看:87
本文介绍了具有非最终成员的不可变Java类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在掌握Java中不变性的概念方面,我仍然遇到一些问题.我知道它与C ++中的const -ness不同,并且仅具有自身不可变类的final成员的final类是不可变的.例如.以下类是不可变的:

I still have some problems grasping the idea of immutability in Java. I understand that it differs from the const-ness in C++ and that a final class that only has final members of classes that are immutable themselves is immutable. E.g. the following class is immutable:

public final class A {
    final String x;
    final int y;

    public A(String x, String y) {
        this.x = x;
        this.y = y;
    }
}

除了此处所示的准则外,是否还有一些正式的定义其他地方的东西?

Is there some formal definition besides the guidelines presented here and similar stuff somewhere else?

请考虑以下示例. Person是不可变的吗?除了使成员motherfather final之外,还有一种方法使其不可变.我不能将它们设为final,因为我必须使用任意排序从输入文件中构建People对象的列表,并且不想对该输入执行拓扑排序.另外,应该可以表示周期的情况.

Consider the following example. Is Person immutable? Is there a way to make it immutable besides making the members mother and father final. I cannot make them final because I have to build a list of People objects from an input file with arbitrary sorting and do not want to perform topological sort on this input. Also, the case of cycles should be possible to be represented.

public final class Person {
    Person father = null;
    Person mother = null;
    public final String name;

    Person(String name) { this.name = name; }

    public Person getFather() { return father; }
    public Person getMother() { return mother; }
}

// in the same package

public class TrioBuilder {
    // build trio of child, mother, and father
    public static ArrayList<Person> build(String c, String m, String f) {
        Person child = new Person(c);
        Person mother = new Person(m);
        Person father = new Person(f);

        child.father = father;
        child.mother = mother;

        ArrayList<Person> result = new ArrayList<Person>();
        result.add(child);
        result.add(mother);
        result.add(father);
        return result;
    }
}

推荐答案

人是一成不变的吗?

Is Person immutable?

不,不是.

一个不可变的类是final,并且只有final个成员.

An immutable class is final and only has final members.

在您的情况下,您要使用的是一个构建器类:

In your case, what you want to use is a builder class:

final Person person = new PersonBuilder().withFather(xx).withMother(xx).build();

通过这种方式,您可以使Person final的所有成员成为成员,并且由于Person本身是最终的,因此您将获得一个真正的不可变类.

This way you can make all members of Person final, and since Person is itself final, you get a real immutable class.

这篇关于具有非最终成员的不可变Java类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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