Java: cloning arbitrary collections by referencing collections

Suppose you have a method of type Java util. Collection, and it can't be said which Java it will point to at run time util. Implementation of collection, can collection be cloned?

I want to implement a generic method that will filter collections of any given type Therefore, this method will use Java util. Collection as input However, beyond that, I don't want to modify the original collection, so I want to clone the collection

Solution

I see three options:

>Rely on the collection's own cloning method (assuming it implements clonable), and then delete unwanted elements Editor: as pointed out in the comments and other answers, clone () is not public and therefore inaccessible. > The caller is requested to provide an empty collection to copy the target element between the source and the target. > Define a factory interface to create an empty collection and require the caller to provide a factory implementation Then copy the target element between the source and destination

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>