Java 中如何在 ArrayList 和 TreeSet 之间共享元素?
我想同时修改ArrayList和TreeSet的元素。
前任。当我修改 TreeSet 中的元素时,Arraylist 中相应的元素也会被修改。
I want to modify the elements of the ArrayList and TreeSet simultaneously.
Ex. When I modify an element from the TreeSet, the corresponding element in the Arraylist is modified too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只要您向两者添加相同的对象,这正是应该发生的情况。 (我是不是漏掉了什么?)
As long as you're adding the same object to both, this is exactly what should happen. (Am I missing something?)
在 Java 中,集合中的对象与其引用一起存储。因此,如果您修改一个对象,它将在引用它的所有地方进行更新。你不应该担心这个。
为了使用同步,您应该实现一个新类,这是模板:
我上面考虑的事情:
synchronized
关键字提供一致的多线程并发性。上面我没有考虑到的事情:
Collection
一样返回boolean
。您应该实现自己的代码以获得更好的解决方案,但一般来说,这就是想法。
编辑:另一种解决方案是编写自己的 TreeSet 和 ArrayList 包装器(在下面使用 Treeset 和 arraylist),并且在添加某些内容时,因为您将覆盖该
add()
方法,你可以添加其他的东西。但这并不是松散耦合的做法。也许观察者框架还有另一种解决方案。In Java, objects in collections are stored with their references. Therefore if you modify an object, it will be updated on everywhere it is referenced from. You shouldn't be concerned about that.
In order to use both synchronized you should implement a new class, here's the template:
Things I considered above:
synchronized
keyword to provide consistent multithreaded concurrency.Things I haven't considered above:
boolean
as all javaCollection
s do.You should implement your own code for better solution, but generally, that's the idea.
EDIT: Another solution is to write your own TreeSet and ArrayList wrappers (that uses treeset and arraylist underneath) and when something is added, since you'll override that
add()
method, you can add the other thing. But this is not a loose coupling practice. Maybe there's another solution with Observer Framework.