I noticed that Google Guava Sets
class offers methods such as newHashSet
taking an Iterable
or Iterator
. The HashSet
class bundled with Java already offers a constructor taking a Collection
thereby giving similar behavior.
So I am curious… What is the advantage of these particular static methods in Guava Sets? Is it simply that there may be Iterable
or Iterator
objects that are not also a Collection
? Or is there some other purpose to the Guava team bothering to include such methods?
Iterable
interface was introduced in Java 1.5 and is a base interface for Collection
interface
HashSet
constructor predates this modification, and I think for compatibility they've left it as is in Java 1.5
Guava, on the other hand was not restricted by this change, and for convenience provides constructor that takes Iterator
.
By default Iterable
constructor tries to cast Iterable
to Collection
and if it's not possible, falls through to extracting its Iterator
and calling Iterator
constructor.
In my view, this gives better flexibility to library users.
One other reason for the existence of Sets
utility class was the long hand writing required in Java 1.5 and 1.6 when calling generic constructors.
This particular issue was solved in 1.7 by introducing diamond operator.
To illustrate.
Before 1.7
ArrayList<String> myList = ...
// See generic parameter repeated
HashSet<String> mySet = new HashSet<String>( myList );
// No such issue for statics
HashSet<String> myGuavaSet = Sets.newHashSet( myList );
After 1.7
ArrayList<String> myList = ...
// Notice diamond
HashSet<String> mySet = new HashSet<>( myList );
// Really no reason now to use Guava for HashSet construction in most cases
According to the Google Guava docs, CollectionUtilitiesExplained:
Whenever possible, Guava prefers to provide utilities accepting an
Iterable
rather than aCollection
. Here at Google, it's not out of the ordinary to encounter a "collection" that isn't actually stored in main memory, but is being gathered from a database, or from another data center, and can't support operations likesize()
without actually grabbing all of the elements.As a result, many of the operations you might expect to see supported for all collections can be found in
Iterables
. Additionally, mostIterables
methods have a corresponding version inIterators
that accepts the raw iterator.The overwhelming majority of operations in the
Iterables
class are lazy: they only advance the backing iteration when absolutely necessary. Methods that themselves returnIterables
return lazily computed views, rather than explicitly constructing a collection in memory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With