How to Serialize a list in java? - java

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.

Related

Instantiating an interface with a concrete class

Suppose for a program that I needed a List of some kind. Any kind of List will do, so I create one.
List<Integer> example = new LinkedList<Integer>();
I've heard that it's good practice, when instantiating your objects, to define them as interfaces, if you are doing something that requires the use of that interface, but not necessarily that specific concrete class. For example, I could have made that "example" list an ArrayList instead.
However, defining my LinkedList to be a List interface in this way limits me. I can't use any of the LinkedList-specific methods, for example. I can only use methods that are in the List interface itself. The only way I've found to use my LinkedList-specific methods are to cast example to a LinkedList, like so:
((LinkedList)example).addLast(1);
...which seems to defeat the purpose, since by casting "example" to be a LinkedList, I may as well have created it and defined it to be a LinkedList in the first place, instead of a List.
So why is it good practice to create concrete classes and define them via interface? Is there something that I am missing?
LinkedList implements several interfaces.
The method addLast() comes from the Deque interface. It could be that's the interface you want to use.
Alternatively you might just need a List, in which case the add() method will append to the list.

Why we should use Interface, instead of concrete types?

When using collections in Java, we are advised to use Interface instead of concrete types.
Like: List<Object> list = new ArrayList<Object>();
But, using ArrayList<Object> list = new ArrayList<Object>(); will also does the same job, right?
Yes, but if you later change your mind and use a LinkedList You have to change much more in your code.
That is the Polymorphism which is the core concept of OOP.
It means ‘a state of having many shapes’ or ‘the capacity to take on different forms’. When applied to OOP , it describes a language’s ability to process objects of various types and classes through a single, uniform interface.
List is a Uniform interface and its Different implementations are like ArrayList ,LinkedList.....etc
Prefer to read :What does it mean to program to a interface?
When you define your list as:
List myList = new ArrayList();
you can only call methods and reference members that belong to List class. If you define it as:
ArrayList myList = new ArrayList();
you'll be able to invoke ArrayList specific methods and use ArrayList specific members in addition to those inherited from List.
Nevertheless, when you call a method of a List class in the first example, which was overridden in ArrayList, then method from ArrayList will be called not the one in the List.
Also the first has the advantage that the implementation of the List can change (to a LinkedList for example), without affecting the rest of the code. This is will be difficult to do with an ArrayList, not only because you will need to change ArrayList to LinkedList everywhere, but also because you may have used ArrayList specific methods.
There's a useful principle: for declared types, use the loosest (vaguest) interface possible (and List is 'looser' than ArrayList).
In practice, this means if you only need to access methods declared in List<Object> on your list instance (which is actually an ArrayList), then declare it as List<Object>. This means you can change your mind on the exact type of list later and you only need to change the line that actually instantiates the ArrayList (or LinkedList or whatever you choose).
This has implications for method signature too: if you were passing around an ArrayList instead of a List, and then changed your mind about it being an ArrayList, you have to go and edit lots of method signatures.
Please read up on Polymorphism if you'd like to know more.
Tangentially related is the Liskov Substitution Principle:
What is the Liskov Substitution Principle?
Interfaces or should I say base calsses are used to generalize things and problems at hand. So when you implement an interface you can always get the specific objects.
For example:
From Animal interface or super class you can always derive specific interfaces or calsses like Lion, but not the other way, becaus its true that a Lion is an animal but several other animals cannot be derived from Lion. Thats why it is advised to make things general and hence use interfaces.
Same applies in your case. You can always get ArrayList and other implementations from a List.
Say you have a class with the following method
public ArrayList<T> foo (ArrayList<T> someInput) {
//Do some operations on someInput here...
return someOutput;
}
Now, what happens if you change the program so that it uses LinkedList objects instead of ArrayList objects? You will get a compiler error wherever this method is called, and you would have to go through and refactor your code so that it accepts LinkedList objects.
If you had programmed to an interface and used a List instead:
public List<T> foo (List<T> someInput) {
//Do some operations on someInput here....
return someOutput;
}
If this was the case, no refactoring would be necessary as both the LinkedList and ArrayList classes implement List so there would be no compiler errors. This makes it incredibly flexible. It does not matter to the method what it takes in and what it returns, as long as the objects implement the List interface. This allows you to define behaviour without exposing any of the underlying implementation.

List<Object> listObject = new ArrayList<Object>()?

So many time I have seen that instantiation of Arraylist is done in the manner "
List<Object> listObject = new ArrayList<Object>();
So I am wondered that what is the significance of instantiation of Arraylist in this way? What happens if we instantiate ArrayList() like
ArrayList<Object> listObject = new ArrayList<Object>();
List is an interface , ArrayList class is a specific implementation of that interface.
List<Object> listObject = new ArrayList<Object>();
With this you can change the List implementation in future. List listObject can invoke all the methods declared in the List interface. In future , if you don't want the ArrayList implementation of the List, and change it with say a LinkedList , you can do that :
List<Object> listObject = new LinkedList<Object>();
You will not have to alter the code which uses listObject , if you had declared the listObject as List interface type, and not worry about it breaking the rest of the code because you might have used something specific to ArrayListwith this declaration:
ArrayList<Object> listObject = new ArrayList<Object>();
This is called Programming to an interface, not to an implementation.
This is because of the fact that its always a good practice to write code to interface and not implementation. So when you do List<Object> listObject = new ArrayList<Object>(); you always have the liberty to change ArrayList to LinkedList and elsewhere in the code will need no change. So programming to interface (List) here gives you the liberty/power to change the underlying implementation without affecting other places in code. I will suggest you to read this small note to have more clarity.
Most of answers refer to the mantra of "coding to the interface". Although, it is a sound advice, it might lead to some problems. Specifically, in case of List the user of object listObject would not know anything about the efficiency of the underlying data structure. For example, if this is an instance of ArrayList then getting the last element is only O(1), while if it is a LinkedList then it is O(listObject.size).
Therefore, often it is very important to know the exact underlying data structure, which can be achieved by using the implementation type for variable declaration. For instance, Scala's List is a class that make its data structure explicit.
Thus, I would say that as always, the decision should be an informed one and cater toward the design of your application. If the data structure should be "a list" and no requirements for specific implementation is known then use List for declaration. However, if a set of algorithms that should work on that data structure is well known then use a concrete implementation class (i.e. ArraysList, LinkedList) that would ensure optimal performance of those algorithms.
There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.
When you define your list as:
List myList = new ArrayList();
you can only call methods and reference members that belong to List class. If you define it as:
ArrayList myList = new ArrayList();
you'll be able to invoke ArrayList specific methods and use ArrayList specific members in addition to those inherited from List.
Nevertheless, when you call a method of a List class in the first example, which was overridden in ArrayList, then method from ArrayList will be called not the one in the List.
That's called polymorphism.
This will ,"Program to an interface and not to an Implementation"
Please have a look at this and this
List is an interface, and ArrayList is a class. Best practices say: Program against interfaces, not concrete classes.
Actually, there may be no difference between those two definitions (defining the variable type as interface vs class), but using List makes your code dependent on the interface, not the class. Then you can later change the actual type of the variable, without affecting the code that is using the variable.
Because you can use different implementations of the same interface(in this case you may want to change your List implementation to a linkedList instead of an ArrayList ) without changing code.
Why should the interface for a Java class be preferred?
As of Java 7 these are the known implementations of List
All Known Implementing Classes:
AbstractList, AbstractSequentialList,
ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList,
RoleUnresolvedList, Stack, Vector
Leaving aside the Abstract classes what this means is that in the future if you want to plug in a different List implementation other than ArrayList you have a variety of options.
Also called Coding to Interfaces this is a widely used programming paradigm.
When you use List you use Abstraction. Imaging a case wherein there is function call expects List<Object>
List<Object> myList = myFunction();
now in function myFunction(),
its better to use
List<Object> myList = new ArrayList<Object>();
return myList;
than
ArrayList<Object> myList = new ArrayList<Object>();
because you will avoid unnecessary casting. The calling function only expects a List irrespective of its implementation.
Moreover, List interface offers a lot of generic functions which are applicable for all the implementations. So you can write some generic code manipulating a list irrespective of whether its LinkedList or ArrayList. This is the advantage of using Abstraction.
List is an Interface. when ever you define interface as reference we have to instantiate using it's implementation.

Why should a Comparator implement Serializable?

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

"Instantiating" a List in Java? [duplicate]

This question already has answers here:
How to initialize List<String> object in Java?
(13 answers)
Closed 8 years ago.
Trying to use the following code:
List<Integer> list = new List<Integer>();
I get the following error message:
java.util.List is abstract; cannot be instantiated
What does this mean and why can't I initialize a List the same way I would an ArrayList?
In Java, List is an interface. That is, it cannot be instantiated directly.
Instead you can use ArrayList which is an implementation of that interface that uses an array as its backing store (hence the name).
Since ArrayList is a kind of List, you can easily upcast it:
List<T> mylist = new ArrayList<T>();
This is in contrast with .NET, where, since version 2.0, List<T> is the default implementation of the IList<T> interface.
List is an interface, not a concrete class.
An interface is just a set of functions that a class can implement; it doesn't make any sense to instantiate an interface.
ArrayList is a concrete class that happens to implement this interface and all of the methods in it.
Use List<Integer> list = new ArrayList<Integer>();
List is the interface, not a class so it can't be instantiated. ArrayList is most likely what you're after:
ArrayList<Integer> list = new ArrayList<Integer>();
An interface in Java essentially defines a blueprint for the class - a class implementing an interface has to provide implementations of the methods the list defines. But the actual implementation is completely up to the implementing class, ArrayList in this case.
The JDK also provides LinkedList - an alternative implementation that again conforms to the list interface. It works very differently to the ArrayList underneath and as such it tends to be more efficient at adding / removing items half way through the list, but for the vast majority of use cases it's less efficient. And of course if you wanted to define your own implementation it's perfectly possible!
In short, you can't create a list because it's an interface containing no concrete code - that's the job of the classes that implement that list, of which ArrayList is the most used by far (and with good reason!)
It's also worth noting that in C# a List is a class, not an interface - that's IList. The same principle applies though, just with different names.
A List isn't a real thing in Java. It's an interface, a way of defining how an object is allowed to interact with other objects. As such, it can't ever be instantiated. An ArrayList is an implementation of the List interface, as is a linked list, and so on. Use those instead.
A List in java is an interface that defines certain qualities a "list" must have. Specific list implementations, such as ArrayList implement this interface and flesh out how the various methods are to work. What are you trying to accomplish with this list? Most likely, one of the built-in lists will work for you.

Categories

Resources