从对象获取列表,修改并设置为一行
我需要从对象中获取 list<示例>
,向其添加一个元素,然后将修改后的列表附加到对象。在一行中,有什么明智的方法?现在看起来如下:
List<Example> examples = user.getExamples();
examples.add(example);
user.setExamples(examples);
我想到了这样的SMTH:
user.setExamples(user.getExamples().add(example));
但是由于那不起作用
添加
返回<代码> true
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在面向对象的编程,您应该考虑一个要求对象的“做”它的事情“而不是您试图从外部操纵其内部。
因此,不要提取,操纵和重新注射,而只要求该对象添加一个项目。您甚至都不知道该对象内部的列表是否是。让对象照料物品可以看到合适。
换句话说,拥有和固定器通常是面向对象的设计差的标志。
如果您坚持外部修改:
list#add add
addtrue
,我将添加,因为
false
表示添加失败。要使用设置器,您必须进行多个语句。
如果该返回的列表不可修改,则需要制作一个新列表。将无法解码的列表传递给构造函数。
In object-oriented programming, you should think in terms of asking an object to "do its thing" rather than you trying to manipulate its innards from outside.
So rather than extract, manipulate, and re-inject, simply ask that object to add an item. You don't even know if there is a list inside that object. Let the object take care of tracking items as it sees fit.
In other words, having getters and setters is often a sign of poor object-oriented design.
If you insist on external modifications:
List#add
on the object returned by the getter. I would add anif
test to verify you got backtrue
, as afalse
means the addition failed.To use the setter, you must make multiple statements.
If that returned list is not modifiable, you'll need to make a new one. Pass the unmodifiable list to the constructor.
如果您真的想在一行中使用它,那么这是一种可能适合您要求的方法。:
If you really want to use it in one line, then this is one of approach which might suits your requirement.:
如果您想加入一个元素(或特别是列表),并将串联集合返回一行,则可以执行以下操作:
或在您的具体情况下:
请注意,这可以使用
.tolist()
流中
在Java 16中介绍的方法。对于早期版本,您可以使用.collect(collectors.tolist())
。这可能不是最干净的方法(当然比集合上的简单
.add()
更详细),但是对于您想在一行中声明串联集合的情况,这可能是很好的,与其将其初始化为一个(也许具有误导性变量名称),而是将其添加到另一个。希望这有帮助!
If you're looking to join a Collection (or specifically a List) with a single element and have the concatenated Collection returned in one line, you could do the following:
Or in your specific case:
Note that this makes use of the
.toList()
method onStream
introduced in Java 16. For earlier versions you can use.collect(Collectors.toList())
.This may not be the cleanest approach (it's certainly more verbose than a simple
.add()
on a Collection), but it can be nice for situations where you want to declare the concatenated collection in one line, rather than initializing it in one (with perhaps a misleading variable name), and adding to it in another.Hope this helps!