Google Guava is an open-source set of common libraries for Java , mainly developed by Google engineers.
61-563: Google Guava can be roughly divided into three components: basic utilities to reduce manual labor to implement common methods and behaviors, an extension to the Java collections framework (JCF) formerly called the Google Collections Library , and other utilities which provide convenient and productive features such as functional programming , graphs , caching , range objects, and hashing . The creation and architecture of
122-544: A Collection<Object> object an creates a new instance of this object with return type ArrayList<Long> , the Java compiler will (correctly) throw a compile-time exception to indicate the presence of incompatible types (since generics are invariant). Hence, this avoids potential run-time exceptions. This problem can be fixed by creating an instance of Collection<Object> using ArrayList<Object> object instead. For code using Java SE7 or later versions,
183-587: A ConcurrentLinkedQueue , the Java Collection Library guarantees that the element is safely published by allowing any thread to get the element from the collection. An object is said to be safely published if the object's state is made visible to all other thread at the same point in time. Safe publication usually requires synchronization of the publishing and consuming threads. The java.util.concurrent.BlockingQueue interface extends Queue . The BlockingQueue interface has
244-433: A Number that is not an Integer into it; which violates type safety. Here is an example that demonstrates how type safety would be violated if List<Integer> were a subtype of List<Number> : The solution with wildcards works because it disallows operations that would violate type safety: To specify the lower bounding class of a type wildcard, the super keyword is used. This keyword indicates that
305-440: A String to this Long[] object, the java program will throw an ArrayStoreException . On the other hand, if the developer instead declared a new instance of a Collection<Object> as ArrayList<Long> , the Java compiler will (correctly) throw a compile-time exception to indicate that the code is written with incompatible and incorrect type, thus preventing any potential run-time exceptions.The developer can fix
366-515: A Vector to be treated as a Stack . The usual push(E e) and pop() operations are provided, as well as a method ( peek() ) to peek at the top item on the Stack , a method to test for whether the Stack is empty ( empty() ), and a method to search the Stack for an item and discover how far it is from the top ( search(Object o) ). When a Stack is first created, it contains no items. The CopyOnWriteArrayList extends
427-459: A compile-time error (with J2SE 5.0 or later) because the compiler will detect that v.get(0) returns String instead of Integer . For a more elaborate example, see reference. Here is a small excerpt from the definition of the interfaces java.util.List and java.util.Iterator in package java.util : Here is an example of a generic Java class, which can be used to represent individual entries (key to value mappings) in
488-402: A map : This generic class could be used in the following ways, for example: It outputs: Here is an example of a generic method using the generic class above: Note: If we remove the first <Type> in the above method, we will get compilation error (cannot find symbol "Type"), since it represents the declaration of the symbol. In many cases, the user of the method need not indicate
549-653: A group. However, unlike arrays, Collection s do not need to be assigned a certain capacity when instantiated. Collection s can grow and shrink in size automatically when objects are added or removed. Collection s cannot hold primitive data types such as int , long , or double . Instead, Collection s can hold wrapper classes such as java.lang.Integer , java.lang.Long , or java.lang.Double . Collection s are generic and hence invariant, but arrays are covariant . This can be considered an advantage of generic objects such as Collection when compared to arrays, because under circumstances, using
610-419: A key is an identification card. The base interface for dictionaries/maps is called Map . Lists are finite collections where it can store the same value multiple times. Sets are unordered collections that can be iterated and contain each element at most once. The base interface for sets is called Set . Lists are implemented in the collections framework via the java.util.List interface. It defines
671-527: A list as essentially a more flexible version of an array. Elements have a specific order, and duplicate elements are allowed. Elements can be placed in a specific position. They can also be searched for within the list. There are several concrete classes that implement List , including AbstractList and all of its corresponding subclasses, as well as CopyOnWriteArrayList . The direct subclasses of AbstractList class include AbstractSequentialList , ArrayList and Vector . AbstractList
SECTION 10
#1732773326288732-473: A performance overhead. For scenarios where synchronization is not mandatory, then the CopyOnWriteArrayList is a viable, thread-safe alternative to synchronization that leverages multi-core processors and results in higher CPU utilization. The java.util.Queue interface defines the queue data structure, which stores elements in the order in which they are inserted. New additions go to
793-449: A result. Sun Microsystems chose not to use the ideas of JGL, because they wanted a compact framework, and consistency with C++ was not one of their goals. Doug Lea later developed a concurrency package , comprising new Collection-related classes. An updated version of these concurrency utilities was included in JDK 5.0 as of JSR 166 . Almost all collections in Java are derived from
854-559: A type wildcard, the extends keyword is used to indicate that the type argument is a subtype of the bounding class. So List <? extends Number > means that the given list contains objects of some unknown type which extends the Number class. For example, the list could be List<Float> or List<Number> . Reading an element from the list will return a Number . Adding null elements is, again, also allowed. The use of wildcards above adds flexibility since there
915-523: Is an example of a skeletal implementation , which leverages and combines the advantages of interfaces and abstract classes by making it easy for the developer to develop their own implementation for the given interface. The java.util.ArrayList class implements the List as an array. Whenever functions specific to a List are required, the class moves the elements around within the array in order to do it. The java.util.LinkedList class stores
976-409: Is an example of a skeletal implementation . The java.util.PriorityQueue class implements java.util.Queue , but also alters it. PriorityQueue has an additional comparator() method. Instead of elements being ordered in the order in which they are inserted, they are ordered by priority. The method used to determine priority is either the java.lang.Comparable#compareTo(T) method in
1037-610: Is combined with the Deque function. Java's java.util.Set interface defines the Set . A Set can't have any duplicate elements in it. Additionally, the Set has no set order. As such, elements can't be found by index. Set is implemented by java.util.HashSet , java.util.LinkedHashSet , and java.util.TreeSet . There are several implementations of the Set interface, including AbstractSet and its subclasses, and
1098-465: Is implemented by java.util.ArrayDeque and java.util.LinkedList . LinkedList , of course, also implements the List interface and can also be used as one. But it also has the Queue methods. LinkedList implements the java.util.Deque interface, giving it more flexibility. ArrayDeque implements the Queue as an array. Similar to LinkedList , ArrayDeque also implements
1159-409: Is not any inheritance relationship between any two parameterized types with concrete type as type argument. Neither List<Number> nor List<Integer> is a subtype of the other; even though Integer is a subtype of Number . So, any method that takes List<Number> as a parameter does not accept an argument of List<Integer> . If it did, it would be possible to insert
1220-428: Is not supported is due to type erasure: Due to type erasure, the runtime will not know which catch block to execute, so this is prohibited by the compiler. Java generics differ from C++ templates . Java generics generate only one compiled version of a generic class or function regardless of the number of parameterizing types used. Furthermore, the Java run-time environment does not need to know which parameterized type
1281-444: Is used because the type information is validated at compile-time and is not included in the compiled code. Consequently, instantiating a Java class of a parameterized type is impossible because instantiation requires a call to a constructor, which is unavailable if the type is unknown. For example, the following code cannot be compiled: Because there is only one copy per generic class at runtime, static variables are shared among all
SECTION 20
#17327733262881342-462: The java.util.Collection interface. Collection defines the basic parts of all collections. The interface has the add(E e) and remove(E e) methods for adding to and removing from a Collection respectively. It also has the toArray() method, which converts the Collection into an array of Object s in the Collection (with return type of Object[] ). Finally,
1403-477: The java.util.Deque interface. The java.util.concurrent.BlockingDeque interface extends java.util.concurrent.BlockingQueue . BlockingDeque is similar to BlockingQueue . It provides the same methods for insertion and removal with time limits for waiting for the insertion or removal to become possible. However, the interface also provides the flexibility of a Deque . Insertions and removals can take place at both ends. The blocking function
1464-413: The contains(E e) method checks if a specified element exists in the Collection . The Collection interface is a subinterface of java.lang.Iterable , so any Collection may be the target of a for-each statement. (The Iterable interface provides the iterator() method used by for-each statements.) All Collection s have an java.util.Iterator that goes through all of
1525-421: The Collection holds. There are several generic types of Collection : Queues , maps , lists and sets . Queues allow the programmer to insert items in a certain order and retrieve those items in the same order. An example is a waiting list. The base interfaces for queues are called Queue . Dictionaries/Maps store references to objects with a lookup key to access the object's values. One example of
1586-663: The Collection<Object> can be instantiated with an ArrayList<> object using the diamond operator Arrays are reified , meaning that an array object enforces its type information at run-time, whereas generics in Java are not reified. More formally speaking, objects with generic type in Java are non-reifiable types. A non-reifiable type is type whose representation at run-time has less information than its representation at compile-time. Objects with generic type in Java are non-reifiable due to type erasure. Java only enforces type information at compile-time. After
1647-511: The Object class, and does not extend any other classes. CopyOnWriteArrayList allows for thread-safety without performing excessive synchronization. In some scenarios, synchronization is mandatory. For example, if a method modifies a static field, and the method must be called by multiple threads, then synchronization is mandatory and concurrency utilities such as CopyOnWriteArrayList should not be used. However synchronization can incur
1708-436: The Queue interface. Deque creates a double-ended queue. While a regular Queue only allows insertions at the rear and removals at the front, the Deque allows insertions or removals to take place both at the front and the back. A Deque is like a Queue that can be used forwards or backwards, or both at once. Additionally, both a forwards and a backwards iterator can be generated. The Deque interface
1769-763: The RegularEnumSet no longer provided any performance benefits for small enum types, it could be removed from the library without negatively impacting the Java Collection Library. Generics in Java#Diamond operator Generics are a facility of generic programming that were added to the Java programming language in 2004 within version J2SE 5.0. They were designed to extend Java's type system to allow "a type or method to operate on objects of various types while providing compile-time type safety". The aspect compile-time type safety required that parametrically polymorphic functions are not implemented in
1830-460: The Stack (method push(E e) ) and to get objects from the Stack (method pop() ). A Stack returns the object according to last-in-first-out (LIFO), e.g. the object which was placed latest on the Stack is returned first. java.util.Stack is a standard implementation of a stack provided by Java. The Stack class represents a last-in-first-out (LIFO) stack of objects. The Stack class has five additional operations that allow
1891-455: The Java virtual machine , since type safety is impossible in this case. The Java collections framework supports generics to specify the type of objects stored in a collection instance. In 1998, Gilad Bracha , Martin Odersky , David Stoutamire and Philip Wadler created Generic Java, an extension to the Java language to support generic types. Generic Java was incorporated in Java with
Google Guava - Misplaced Pages Continue
1952-423: The diamond operator ) for a pair of angle brackets containing the one or more type parameters that a sufficiently close context implies . Thus, the above code example using Entry can be rewritten as: A type argument for a parameterized type is not limited to a concrete class or interface. Java allows the use of "type wildcards" to serve as type arguments for parameterized types. Wildcards are type arguments in
2013-528: The Java platform included few data structure classes, but did not contain a collections framework. The standard methods for grouping Java objects were via the array, the Vector , and the Hashtable classes, which unfortunately were not easy to extend, and did not implement a standard member interface. To address the need for reusable collection data structures , several independent frameworks were developed,
2074-401: The Java platform libraries, since in computer science , a vector is generally not a stack . Composition would have been more appropriate in this scenario. The Stack class extends class java.util.Vector with five operations that allow a Vector to be treated as a Stack . Stacks are created using java.util.Stack . The Stack offers methods to put a new object on
2135-525: The addition of wildcards . According to Java Language Specification : The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object . Then, it adds a String to the ArrayList . Finally, it attempts to retrieve the added String and cast it to an Integer βan error in logic, as it is not generally possible to cast an arbitrary string to an integer. Although
2196-409: The angle brackets declares the ArrayList to be constituted of String (a descendant of the ArrayList 's generic Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as String by the code generated by the compiler. The logical flaw in the third line of this fragment will be detected as
2257-462: The book Effective Java by Joshua Bloch gives an easy way to remember when to use wildcards (corresponding to covariance and contravariance ) in Java. Although exceptions themselves cannot be generic, generic parameters can appear in a throws clause: Generics are checked at compile-time for type-correctness. The generic type information is then removed in a process called type erasure . For example, List<Integer> will be converted to
2318-414: The code by instantianting Collection<Object> as an ArrayList<Object> object. If the code is using Java SE7 or later versions, the developer can instatiate Collection<Object> as an ArrayList<> object by using the diamond operator Collection s are generic and hence reified , but arrays are not reified. Collection implementations in pre- JDK 1.2 versions of
2379-437: The code is compiled without error, it throws a runtime exception ( java.lang.ClassCastException ) when executing the third line of code. This type of logic error can be detected during compile time by using generics and is the primary motivation for using them. It defines one or more type variables that act as parameters. The above code fragment can be rewritten using generics as follows: The type parameter String within
2440-668: The collection component were partly motivated by generics introduced in JDK 1.5. Although generics improve the productivity of programmers, the standard JCF does not provide sufficient functionality, and its complement Apache Commons Collections had not adopted generics in order to maintain backward compatibility . This fact led two engineers Kevin Bourrillion and Jared Levy to develop an extension to JCF, which provides additional generic classes such as multisets , multimaps , bitmaps , and immutable collections. The library's design and code were advised and reviewed by Joshua Bloch ,
2501-411: The element type of the Collection<E> generic interface. When the actual type argument is ? , it stands for some unknown type. Any method argument value we pass to the add() method would have to be a subtype of this unknown type. Since we don't know what type that is, we cannot pass anything in. The sole exception is null ; which is a member of every type. To specify the upper bound of
Google Guava - Misplaced Pages Continue
2562-415: The elements in nodes that each have a pointer to the previous and next nodes in the List . The List can be traversed by following the pointers, and elements can be added or removed simply by changing the pointers around to place the node in its proper place. The Vector class has Stack as its direct subclass. This is an example of a violation of the composition over inheritance principle in
2623-461: The elements in the Collection . Collection is generic. Any Collection can store any Object . For example, any implementation of Collection<String> contains String objects. No casting is required when using the String objects from an implementation of Collection<String> . Note that the angled brackets < > can hold a type argument that specifies which type
2684-410: The elements, or a method given in the constructor. The class creates this by using a heap to keep the items sorted. The java.util.concurrent.ConcurrentLinkedQueue class extends java . util . AbstractQueue . ConcurrentLinkedQueue implements the java . util . Queue interface. The ConcurrentLinkedQueue class is a thread-safe collection, since for any an element placed inside
2745-654: The end of the line, and elements are removed from the front. It creates a first-in first-out system. This interface is implemented by java.util.LinkedList , java.util.ArrayDeque , and java.util.PriorityQueue . The direct subclasses of AbstractQueue class include ArrayBlockingQueue , ConcurrentLinkedQueue , DelayeQueue , LinkedBlockingDeque , LinkedBlockingQueue . LinkedTransferQueue and PriorityBlockingQueue . Note that ArrayDeque and ConcurrentLinkedDeque both extend AbstractCollection but do not extend any other abstract classes such as AbstractQueue . AbstractQueue
2806-536: The final static inner class ConcurrentHashMap . KeySetView < K , V > (where K and V are formal type parameters). AbstractSet is a skeletal implementation for the Set interface. Direct subclasses of AbstractSet include ConcurrentSkipListSet , CopyOnWriteArraySet , EnumSet , HashSet and TreeSet . The EnumSet class extends AbstractSet . The EnumSet class has no public constructors, and only contain static factory methods. EnumSet contains
2867-471: The following direct sub-interfaces: BlockingDeque and TransferQueue . BlockingQueue works like a regular Queue , but additions to and removals from the BlockingQueue are blocking. If remove(Object o) is called on an empty BlockingQueue , it can be set to wait either a specified time or indefinitely for an item to appear in the BlockingQueue . Similarly, adding an item using
2928-493: The form " <?> "; optionally with an upper or lower bound . Given that the exact type represented by a wildcard is unknown, restrictions are placed on the type of methods that may be called on an object that uses parameterized types. Here is an example where the element type of a Collection<E> is parameterized by a wildcard: Since we don't know what the element type of c stands for, we cannot add objects to it. The add() method takes arguments of type E ,
2989-459: The generic Collection instead of an array prevents run time exceptions by instead throwing a compile-time exception to inform the developer to fix the code. For example, if a developer declares an Object[] object, and assigns the Object[] object to the value returned by a new Long[] instance with a certain capacity, no compile-time exception will be thrown. If the developer attempts to add
3050-421: The instances of the class, regardless of their type parameter. Consequently, the type parameter cannot be used in the declaration of static variables or in static methods. Type erasure was implemented in Java to maintain backward compatibility with programs written prior to Java SE5. There are several important differences between arrays (both primitive arrays and Object arrays), and generics in Java. Two of
3111-448: The major differences, namely, differences in terms of variance and reification . Generics are invariant, whereas arrays are covariant . This is a benefit of using generic when compared to non-generic objects such as arrays. Specifically, generics can help prevent run time exceptions by throwing a compile-time exception to force the developer to fix the code. For example, if a developer declares an Object[] object and instantiates
SECTION 50
#17327733262883172-426: The method add(Object o) is subject to an optional capacity restriction on the BlockingQueue , and the method can wait for space to become available in the BlockingQueue before returning. BlockingQueue interface introduces a method take() which removes and gets the head of the BlockingQueue , and waits until the BlockingQueue is no longer empty if required. The Deque interface extends
3233-491: The most used being Doug Lea 's Collections package , and ObjectSpace Generic Collection Library (JGL), whose main goal was consistency with the C++ Standard Template Library (STL). The collections framework was designed and developed primarily by Joshua Bloch , and was introduced in JDK 1.2 . It reused many ideas and classes from Doug Lea's Collections package , which was deprecated as
3294-579: The non-generic type List , which ordinarily contains arbitrary objects. The compile-time check guarantees that the resulting code uses the correct type. Because of type erasure, type parameters cannot be determined at run-time. For example, when an ArrayList is examined at runtime, there is no general way to determine whether, before type erasure, it was an ArrayList<Integer> or an ArrayList<Float> . Many people are dissatisfied with this restriction. There are partial approaches. For example, individual elements may be examined to determine
3355-420: The object as a new Long[] object, no compile-time exception is thrown (since arrays are covariant). This may give the false impression that the code is correctly written. However, if the developer attempts to add a String to this Long[] object, the program will throw an ArrayStoreException . This run-time exception can be completely avoided if the developer uses generics. If the developer declares
3416-586: The original lead designer of the Java Collections framework, and Doug Lea , one of the lead designers of concurrency utilities in JDK . As of April 2012, Guava ranked the 12th most popular Java library, next to the Apache Commons projects and a few others. Research performed in 2013 on 10,000 GitHub projects found that Google-made libraries, such as Google Web Toolkit and Guava, constituted 7 of
3477-405: The static factory method EnumSet . of () . This method is an aggregation method. It takes in several parameters, takes into account of the type of the parameters, then returns an instance with the appropriate type. As of 2018, In Java SE8 OpenJDK implementation uses two implementations of EnumSet which are invisible to the client, which are RegularEnumSet and JumboEnumSet . If
3538-581: The top 100 most popular libraries in Java, and that Guava was the 8th most popular Java library. Java collections framework The Java collections framework is a set of classes and interfaces that implement commonly reusable collection data structures . Although referred to as a framework , it works in a manner of a library . The collections framework provides both interfaces that define various collections and classes that implement them. Collection s and arrays are similar in that they both hold references to objects and they can be managed as
3599-467: The type argument is a supertype of the bounding class. So, List <? super Number > could represent List<Number> or List<Object> . Reading from a list defined as List <? super Number > returns elements of type Object . Adding to such a list requires either elements of type Number , any subtype of Number or null (which is a member of every type). The mnemonic PECS (Producer Extends, Consumer Super) from
3660-471: The type parameters, as they can be inferred: The parameters can be explicitly added if needed: The use of primitive types is not allowed, and boxed versions must be used instead: There is also the possibility to create generic methods based on given parameters. In such cases you can't use primitive types either, e.g.: Thanks to type inference , Java SE 7 and above allow the programmer to substitute an empty pair of angle brackets ( <> , called
3721-522: The type they belong to; for example, if an ArrayList contains an Integer , that ArrayList may have been parameterized with Integer (however, it may have been parameterized with any parent of Integer , such as Number or Object ). Demonstrating this point, the following code outputs "Equal": Another effect of type erasure is that a generic class cannot extend the Throwable class in any way, directly or indirectly: The reason why this
SECTION 60
#1732773326288#287712