What is the difference between Collection and AbstractCollection in Java? - java

Edit: what i am actually meant to ask about is why do we need an abstract class, a hash class, etc implementing interfaces like map, set and collection?? What is the difference between those (abstractmap, hashmap, map) and why do they need to be interfaces?

If you want to implement a collection, it is easier to extend AbstractCollection which has already some methods of Collection implemented, than to implement the whole Collection interface.
From documentation of AbstractCollection:
This class provides a skeletal implementation of the Collection interface, to minimize the effort required to implement this interface.

Related

what is the proper way to implement the java Collection interface

I'm not sure what is the proper way to override all methods in Collection<E> interface.
I was asked to create a Class HotDog implements Collection<E>, thus i must override all methods it contains and I'm not sure how to do this since normally I believe the best solution would be to inherit from a class that allready implements Collection interface.
The requirements would be to have the functionality of a HotDog Object for the purposes of calculating the full price of the HotDog depending on the amount of ingredients the hotdog has, I believe the Collection functionality is for the ingredients in the hotdog.
There are three ways to create a new collection:
From scratch. You implement all methods of the Collection interface.
Extending an existing class, like you already mentioned. Java offers abstract classes for this purpose: java.util.AbstractCollection and various implementations for specific kinds of collection. These abstract classes allow you to focus on how the collections stores its elements instead of having to write all methods yourself.
Composition. Your class is basically a wrapper for an existing collection class and redirects all its method calls (except for a few whose behavior you want to adapt) directly to the wrapped collection's methods.
Which method is best depends on your particular requirements.

Why is Java 'Comparable' better than just using a compareTo method?

I see that Comparable interface allowed implementation of just the compareTo method. So why do we even need this interface? Why can't we simply define and declare the method in any class we want, without having to implement the Comparable interface?
I understand that this is correct: SortedSet<String> exampleSet = new TreeSet<String>(); <-- TreeSet implements SortedSet interface. So if I have a class called "Date" that implements Comparable, is this correct: Comparable<Date> example = new Date<Date>();. If yes, what exactly do I get? I mean what kind of object do I get? What properties does it have? If not, why not?
Why can't we simply define and declare the method in any class we want, without having to implement the Comparable interface?
How would you expect a sorting method to work in that case?
It's really handy to be able to sort any collection where the elements are all comparable with each other - and an interface is the way to express that.
is this correct: Comparable<Date> example = new Date<Date>();
No, not unless Date itself were generic. You could write:
Comparable<Date> example = new Date();
... but it would be odd to do so. Normally Comparable is used by code which wants to compare existing objects - so it would fetch values from a collection and compare them with each other, for example.
Why can't we simply define and declare the method in any class we
want, without having to implement the Comparable interface?
Some Collections like TreeMap, need to compare two objects, even for a simple add() operation. Such a tree needs that to internally put "smaller" object in the left tree, and bigger ín the right subtree (a bit simplified).
Because such a generic Collection (like TreeMap), is designed to work for all Objects, the Object, then must know how to perfrom a compareTo().
Other Collections like HashMaps do not need that the Objects implement Comparable (They use hashcode())

Java interface extends interface in the java.util package

As we know, interfaces can extend interface in the Java. I have a question about this, if interface B extends interface A, B need not implement the methods defined in the A. But in the java.util package, the List interface extends Collection interface, and it implements the Collection method, these methods also just have the method declaration.
Why does it do this, and it there a better practice? Does it make any difference between implementing the method in the sub interface or not?
Overriding a method, besides providing/replacing a method implementation, allows to provide a more specific javadoc, and to narrow the return type.
For instance, Collection.iterator() is specified by:
Returns an iterator over the elements in this collection. There are no
guarantees concerning the order in which the elements are returned
(unless this collection is an instance of some class that provides a
guarantee).
while List.iterator() is specified by
Returns an iterator over the elements in this list in proper sequence.
I don't see any implementation in java.util.List but declarations. Instead the javadocs of List say,
The List interface places additional stipulations, beyond
those specified in the Collection interface, on the
contracts of the iterator, add, remove,
equals, and hashCode methods. Declarations for
other inherited methods are also included here for convenience.
The interface List do not implement Collections' methods because interfaces just cannot implement methods, they just declare them. An interface is like a 100% abstract class: all the methods must be abstract methods.
Probably your confusion comes from abstract classes that implement interfaces: these classes must not implement interface's methods (despite being allowed to), only the first concrete class must.
Interfaces are fully abstract in Java. They can't have any implementation.
Redeclaring a method is not the same as implementing it. And it doesn't make any sense to redeclare a method (if the method signature is exactly same), because the purpose of an interface extending another interface is to add some more-specific method declarations, and not to just redeclare the existing ones.
Edit
As pointed out in #Arham's and #meriton's answer, the purpose of the redeclaration is to respecify the method according to the sub-interface. So, for a client code, accessing the underlying collection, there would be a separate more-specific specification on the redeclared methods than the more-general one in the super-interface.

Why do many Collection classes in Java extend the abstract class and implement the interface as well?

Why do many Collection classes in Java extend the Abstract class and also implement the interface (which is also implemented by the given abstract class)?
For example, class HashSet extends AbstractSet and also implements Set, but AbstractSet already implements Set.
It's a way to remember that this class really implements that interface.
It won't have any bad effect and it can help to understand the code without going through the complete hierarchy of the given class.
From the perspective of the type system the classes wouldn't be any different if they didn't implement the interface again, since the abstract base classes already implement them.
That much is true.
The reason they do implement it anyways is (probably) mostly documentation: a HashSet is-a Set. And that is made explicit by adding implements Set to the end, although it's not strictly necessary.
Note that the difference is actually observable using reflection, but I'd be hard-pressed to produce some code that would break if HashSet didn't implement Set directly.
This may not matter much in practice, but I wanted to clarify that explicitly implementing an interface is not exactly the same as implementing it by inheritance. The difference is present in compiled class files and visible via reflection. E.g.,
for (Class<?> c : ArrayList.class.getInterfaces())
System.out.println(c);
The output shows only the interfaces explicitly implemented by ArrayList, in the order they were written in the source, which [on my Java version] is:
interface java.util.List
interface java.util.RandomAccess
interface java.lang.Cloneable
interface java.io.Serializable
The output does not include interfaces implemented by superclasses, or interfaces that are superinterfaces of those which are included. In particular, Iterable and Collection are missing from the above, even though ArrayList implements them implicitly. To find them you have to recursively iterate the class hierarchy.
It would be unfortunate if some code out there uses reflection and depends on interfaces being explicitly implemented, but it is possible, so the maintainers of the collections library may be reluctant to change it now, even if they wanted to. (There is an observation termed Hyrum's Law: "With a sufficient number of users of an API, it does not matter what you promise in the contract; all observable behaviors of your system will be depended on by somebody".)
Fortunately this difference does not affect the type system. The expressions new ArrayList<>() instanceof Iterable and Iterable.class.isAssignableFrom(ArrayList.class) still evaluate to true.
Unlike Colin Hebert, I don't buy that people who were writing that cared about readability. (Everyone who thinks standard Java libraries were written by impeccable gods, should take look it their sources. First time I did this I was horrified by code formatting and numerous copy-pasted blocks.)
My bet is it was late, they were tired and didn't care either way.
From the "Effective Java" by Joshua Bloch:
You can combine the advantages of interfaces and abstract classes by adding an abstract skeletal implementation class to go with an interface.
The interface defines the type, perhaps providing some default methods, while the skeletal class implements the remaining non-primitive interface methods atop the primitive interface methods. Extending a skeletal implementation takes most of the work out of implementing an interface. This is the Template Method pattern.
By convention, skeletal implementation classes are called AbstractInterface where Interface is the name of the interface they implement. For example:
AbstractCollection
AbstractSet
AbstractList
AbstractMap
I also believe it is for clarity. The Java Collections framework has quite a hierarchy of interfaces that defines the different types of collection. It starts with the Collection interface then extended by three main subinterfaces Set, List and Queue. There is also SortedSet extending Set and BlockingQueue extending Queue.
Now, concrete classes implementing them is more understandable if they explicitly state which interface in the heirarchy it is implementing even though it may look redundant at times. As you mentioned, a class like HashSet implements Set but a class like TreeSet though it also extends AbstractSet implements SortedSet instead which is more specific than just Set. HashSet may look redundant but TreeSet is not because it requires to implement SortedSet. Still, both classes are concrete implementations and would be more understandable if both follow certain convention in their declaration.
There are even classes that implement more than one collection type like LinkedList which implements both List and Queue. However, there is one class at least that is a bit 'unconventional', the PriorityQueue. It extends AbstractQueue but doesn't explicitly implement Queue. Don't ask me why. :)
(reference is from Java 5 API)
Too late for answer?
I am taking a guess to validate my answer. Assume following code
HashMap extends AbstractMap (does not implement Map)
AbstractMap implements Map
Now Imagine some random guy came, Changed implements Map to some java.util.Map1 with exactly same set of methods as Map
In this situation there won't be any compilation error and jdk gets compiled (off course test will fail and catch this).
Now any client using HashMap as Map m= new HashMap() will start failing. This is much downstream.
Since both AbstractMap, Map etc comes from same product, hence this argument appears childish (which in all probability is. or may be not.), but think of a project where base class comes from a different jar/third party library etc. Then third party/different team can change their base implementation.
By implementing the "interface" in the Child class, as well, developer's try to make the class self sufficient, API breakage proof.
In my view,when a class implements an interface it has to implement all methods present in it(as by default they are public and abstract methods in an interface).
If we don't want to implement all methods of interface,it must be an abstract class.
So here if some methods are already implemented in some abstract class implementing particular interface and we have to extend functionality for other methods that have been unimplemented,we will need to implement original interface in our class again to get those remaining set of methods.It help in maintaining the contractual rules laid down by an interface.
It will result in rework if were to implement only interface and again overriding all methods with method definitions in our class.
I suppose there might be a different way to handle members of the set, the interface, even when supplying the default operation implementation does not serve as a one-size-fits-all. A circular Queue vs. LIFO Queue might both implement the same interface, but their specific operations will be implemented differently, right?
If you only had an abstract class you couldn't make a class of your own which inherits from another class too.

What is the main difference between Collection and Collections in Java? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
What is the main difference between Collection and Collections in Java?
Collection is a base interface for most collection classes, whereas Collections is a utility class. I recommend you read the documentation.
Are you asking about the Collections class versus the classes which implement the Collection interface?
If so, the Collections class is a utility class having static methods for doing operations on objects of classes which implement the Collection interface. For example, Collections has methods for finding the max element in a Collection.
The Collection interface defines methods common to structures which hold other objects. List and Set are subinterfaces of Collection, and ArrayList and HashSet are examples of concrete collections.
collection : A collection(with small 'c') represents a group of objects/elements.
Collection : The root interface of Java Collections Framework.
Collections : A utility class that is a member of the Java Collections Framework.
Collection, as its javadoc says is "The root interface in the collection hierarchy." This means that every single class implementing Collection in any form is part of the Java Collections Framework.
The Collections Framework is Java's native implementation of data structure classes (with implementation specific properties) which represent a group of objects which are somehow related to each other and thus can be called a collection.
Collections is merely an utility method class for doing certain operations, for example adding thread safety to your ArrayList instance by doing this:
List<MyObj> list = Collections.synchronizedList(new Arraylist<MyObj>());
The main difference in my opinion is that Collection is base interface which you may use in your code as a type for object (although I wouldn't directly recommend that) while Collections just provides useful operations for handling the collections.
Collection is an interface containing List, Set and Queue.
Collections is a class containing useful methods like Collections.sort() and Collections.synchronizedlist(), etc.
Collection is an root interface of Java collection framework.
Collections is a utility class which contains static methods. example Collections.sort()
Collection, as its javadoc says is "The root interface in the collection hierarchy." This means that every single class implementing Collection in any form is part of the Java Collections Framework.
The Collections Framework is Java's native implementation of data structure classes (with implementation specific properties) which represent a group of objects which are somehow related to each other and thus can be called a collection.
Collections is merely an utility method class for doing certain operations, for example adding thread safety to your ArrayList instance by doing this:
List list = Collections.synchronizedList(new Arraylist());
The main difference in my opinion is that Collection is base interface which you may use in your code as a type for object (although I wouldn't directly recommend that) while Collections just provides useful operations for handling the collections.
Collection is an Interface which can used to Represent a Group of Individual object as a single Entity.
Collections is an utility class to Define several Utility Methods for Collection object.
Collection is a interface which is used to represent group of individual object as a single entity.
Collections is an utility class present in java.util. package to define several utility method (like sorting,searching ) for collection object.
Collection is a base interface for most collection classes (it is the root interface of java collection framework)
Collections is a utility class
Collections class is a utility class having static methods It implements Polymorphic algorithms which operate on collections.
The Collections class is a utility class having static methods for doing operations on objects of classes which implement the Collection interface. For example, Collections has methods for finding the max element in a Collection.
Collection is an interface from which other class forms like List, Set are derived.
Collections (with "S") is a utility class having static methods to simplify work on collection. Ex : Collections.sort()
As per Java Doc Collection is:
The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered. The JDK does not provide any direct implementations of this interface: it provides implementations of more specific subinterfaces like Set and List. This interface is typically used to pass collections around and manipulate them where maximum generality is desired.
Where as Collections is:
This class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, "wrappers", which return a new collection backed by a specified collection, and a few other odds and ends.
Collections is a class which has some static methods and that method returns the collection.
Collection is an interface,rather than root interface in collection hierarchy.
Yes, Collections is a utilty class providing many static methods for operations like sorting... whereas Collection in a top level interface.
Collection is a interface and Collections is class in Java.util package
Collections is a utility class, meaning that it defines a set of methods that perform common, often re-used functions, such as sorting a list, rotating a list, finding the minimum value etc.
And these common methods are defined under static scope.
Collection is an interface that is implemented by AbstractCollection which in turn is implemented by AbstractList, AbstractSet etc.
Also,
Collections class has thirty-two convenience implementations of its collection interfaces, providing unmodifiable collections,
synchronized collections. Nearly all of these implementations are
exported via static factory methods in one noninstantiable class (java.util.Collections).
Reference: Effective Java
collection is an interface and it is a root interface for all classes and interfaces like set,list and map.........and all the interfaces can implement collection interface.
Collections is a class that can also implements collection interface.......

Categories