Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Collections.unmodifiableListJava和Ruby 标准 API 中是否有等价物Collections.unmodifiableMap?
Collections.unmodifiableList
Collections.unmodifiableMap
使用freezeAPI:
freeze
防止对 obj 进行进一步修改。如果尝试修改,将引发 RuntimeError。无法解冻冻结的对象。另请参见 Object#frozen?。 此方法返回自我。 a = [ "a", "b", "c" ] a.freeze a << "z" 产生: prog.rb:3:in `<<': can't modify frozen array (RuntimeError) from prog.rb:3
防止对 obj 进行进一步修改。如果尝试修改,将引发 RuntimeError。无法解冻冻结的对象。另请参见 Object#frozen?。
此方法返回自我。
a = [ "a", "b", "c" ] a.freeze a << "z"
产生:
prog.rb:3:in `<<': can't modify frozen array (RuntimeError) from prog.rb:3
您还可以将仓鼠gem 用于其他不可变数据结构。
例如,如果要创建不可修改(不可变)列表:
a = [ "a", "b", "c" ] a.freeze