New to Java. Learning it while working on an Android app. I am implementing a Comparator to sort a list of files and the android docs say that a Comparator should implement Serializable:
It is recommended that a Comparator implements Serializable.
This is the Serializable interface here.
I just want to sort a list of files. Why should I implement this or what even is the reason why it should be for any Comparator?
This is not just an Android thing, the Java SDK has the same recommendation:
Note: It is generally a good idea for comparators to also implement java.io.Serializable, as they may be used as ordering methods in serializable data structures (like TreeSet, TreeMap). In order for the data structure to serialize successfully, the comparator (if provided) must implement Serializable.
So the idea is that because a TreeMap is serializable, and the TreeMap can contain a Comparator, it would be good if the Comparator is also serializable. The same applies for all elements in the collection.
You can safely ignore this unless you use serialization in that way.
Serializeable is a blank interface. It does not contain any methods. So, to implement it, all you need to say is implements Serializable in a class. It's not a huge burden on you. If you extend Comparator, you don't even need to implement Serializable because the super class does that for you, and then you don't need to do anything at all to implement Serializable.
When something implements Serializable, that means the object can be turned into a byte array at will. This is used for transmission over the Internet, storage in a file, etc. Speaking very roughly, the way serialization works for an object, by default, is to take every object referenced by the object you're trying to serialize, turn each such object into a byte array (i.e. invoke serialization on it recursively), and concatenate the byte arrays to produce a byte array that represents the overall object.
Now, why should a Comparator implement Serializable? Let's say you wish to serialize a TreeMap or some other ordered Collection. The goal of serialization is to provide a complete representation of an object. Collections like TreeMap have a Comparator object in them, so to be able to produce a byte array that captures every aspect of such collections, you need to be able to save the Comparator as a byte array too. Hence, Comparator needs to be Serializable so that other things can be properly serialized.
This should help you out : http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html
Note: It is generally a good idea for comparators to implement java.io.Serializable, as they may be used as ordering methods in serializable data structures (like TreeSet, TreeMap). In order for the data structure to serialize successfully, the comparator (if provided) must implement Serializable.
To serialize an object in Java, both these conditions should be satisfied:
The class to which the instance belongs to must implement java.io.Serializable.
The members of the class should be serializable. If one or more of the members are not to be serialized, they should be marked as transient.
When any data structure uses a Comparator and you want that data structure to be serializable, point 2 (mentioned above) compels the comparator to implement serializable.
i have seen in Java 5 API
Link to java 5 APT
which stated that by implementing Comparator doesn't mean to implement Serializable interface anyways, so one has to explicitly pay attention to get Serializable in some customarily created Comparator class
Related
It's all about terminology. Can I say that the List is an abstract data type and the ArrayList is a data structure? So, the Java Collection Framework is group of ASTs and corresponding DSs (implementations).
An interface (not only in Java, but also in e.g. C#, Go etc.) is a definition of the API, a contract, that specifies which methods can be invoked on instances implementing the interface. Interfaces neither hold any data nor actually implement the contract themselves. In that sense one can say that an interface is an abstract data structure. List is an interface, that is it is a contract describing how one can operate with an ordered collection of data. An interface can extend another interface with further contract methods. As the List interfaces describes an ordered collection of data it makes perfect sense that it extends the Collection interface, which simply defines a contract for a generic collection of data (e.g. without referring to a specific ordering or insertion rules). Again, one can describe that as an abstract data structure.
ArrayList is one of possible implementations of the List interface. As such it also implements the Collection interface. So it is a concrete data structure (and a collection itself) implementing more than one abstract data structures. However, there are also abstract classes in Java, those which have some methods left unimplemented. These are also abstract data structures, but are not interfaces. So an interface in Java is an abstract data structure, but not vice versa.
Furthermore, one can have an abstract data structure (abstract class) implementing an interface (an abstract data structure itself). A thought exercise for you: figure what is the meaning of that :)
But then, what is abstract? A concrete class parametrized with a generic type is in a way an abstract data structure as it abstracts away algorithms applicable to different classes that can be used to subsitute the generic type. As ArrayList is itself one of those concrete implementations that uses Java generics to define the data type it operates on, it is itself an abstract data structure, but in a different way from interfaces or abstract classes. The abstract data structure is, in this sense, an ill-defined term.
List is an Interface. You always have an implementation behind it, and you cannot go like:
List list = new List(); // does not work. At least not with java.util.List
ArrayList is one of the implementations that implements the List interface.
So, thus said, you could put it that way.
In Collection framework ,
I am aware Comparable provides single sorting sequence
whereas
Comparator provides multiple sorting sequence
But I am unable to understand how one interface modifies the original data whereas the other does'nt ?
Comparable does not do anything, it's an interface. It forces your object to implement the method 'compareTo'. That allow the object to be compared with another object.
https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html
Comparator does not do anything, it's another interface. It forces your object to implement the method 'compare'. That allow the object to compare two other objects. Note the difference: to be compared and to compare.
https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html
This link explains Object Ordering interfaces very, very well. With examples and everything.
https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html
Why Boolean and Character wrapper classes are implementing Serializable interface and Comparable interface ? What is the use of it?
The Comparable interface was added to the Boolean class in Java 5, to address bug JDK-4329937, and at least one other. One of the issues cited was sorting boolean columns in a JTable.
Initially, there was pushback from no less than Joshua Bloch:
The current design is consistent with the language itself: it is a compile-time error to attempt to compare two booleans for order:
if (true < false) // ERROR: WON'T COMPILE
foo();
The wrapper class (Boolean) merely mirrors the behavior of the wrapped primitive. ...
We would be willing to sacrifice this "design purity" on the altar of pragmatism, but I'm not convinced that there is a real need for comparing Booleans. It is extraordinarily rare to want to sort a list of Booleans. More common is to want to sort a list of objects containing a Boolean field based on this field, but doing this requires the use of a Comparator. If you're writing a Comparator anyway, it's straightforward to sort based on the Boolean field even though Boolean does not, itself, implement Comparable.
But several years later, the utility was acknowledged:
Over the years it has become apparent that it would make life easier for people if we provided this functionality.
Since this enhancement was implemented, it's become even more useful. For example, in Java 8, the Comparator class introduced new methods comparing() and thenComparing, that can build a comparator based on fields. And it can be reasonable and useful to include a boolean field as part of sort criteria.
It implements Serializable so that an object containing it can be serialized. Not making it Serializable would be a serious limitation.
The Comparable isn't so useful as there is only two possible values, so it is likely to be for consistency with other wrappers.
Note: Void is not serializable or comparable, but it can only be null which is serializable.
To use any primitive in most of the Collection classes, they have to implement Comparable. Without the wrapper, you couldn't use a primitive in any ordered Collection classes. Also, as a pure primitive, it doesn't have an equals method, so any key based Collection class wouldn't work.
Here's one. Try instantiating ArrayList<T> with a boolean ...
The basic collection interfaces (List, Map, Set) do not extend Cloneable interface. This is done in order NOT to enforce Cloneability for concrete implementations.
All of the collection classes do implement Cloneable interface so they all are inherently Cloneable. Also Cloneable is a marker interface meaning it signals the compiler/JVM to do some additional work behind the curtain, so as make that object Cloneable.
Now my question is : What the situations where in you DO NOT want your object to be Cloneable?
Singleton is a good case. Another is anything where you have a reference to something on the system that you should only have ONE reference to. For example, a Stream. Having multiple objects point to the same input (or output) stream could cause all kinds of problems.
If you want to use clone(), consider creating a copy constructor instead.
If your class holds a huge chunk of data then you may not want it to be cloned to stop keeping multiple copy of a big chunk of data.
If you were to implement the Singleton pattern, you probably wouldn't want the resulting Singleton to be cloneable.
I wouldn't want to have cloneable threads :X
Neither cloneable resource classes or session beans
I would like to deep clone a List. for that we are having a method
// apache commons method. This object should be serializable
SerializationUtils.clone ( object )
so now to clone my List i should convert that to serializable first. Is it possible to convert a List into Serializable list?
All standard implementations of java.util.List already implement java.io.Serializable.
So even though java.util.List itself is not a subtype of java.io.Serializable, it should be safe to cast the list to Serializable, as long as you know it's one of the standard implementations like ArrayList or LinkedList.
If you're not sure, then copy the list first (using something like new ArrayList(myList)), then you know it's serializable.
As pointed out already, most standard implementations of List are serializable. However you have to ensure that the objects referenced/contained within the list are also serializable.
List is just an interface. The question is: is your actual List implementation serializable? Speaking about the standard List implementations (ArrayList, LinkedList) from the Java run-time, most of them actually are already.