Value-based Classes confusion

前端 未结 5 1637
鱼传尺愫
鱼传尺愫 2021-02-05 18:52

I\'m seeking some clarification to the definition of Value-based Classes. I can\'t imagine, how is the last bullet point (6) supposed to work together with the first one

5条回答
  •  名媛妹妹
    2021-02-05 19:48

    they are freely substitutable when equal, meaning that interchanging any two instances x and y that are equal according to equals() in any computation or method invocation should produce no visible change in behavior

    Once b.get().add("a"); is executed, a is no longer equals to b, so you have no reason to expect assertTrue(a.get().isEmpty()); and assertTrue(b.get().isEmpty()); would produce the same result.

    The fact that a value based class is immutable doesn't mean you can't mutate the values stored in instances of such classes (as stated in though may contain references to mutable objects). It only means that once you create an Optional instance with Optional a = Optional.of(new ArrayList()), you can't mutate a to hold a reference to a different ArrayList.

提交回复
热议问题