I have an implementation of a queue (Queue class, which is basically a linked list) - it consists of linked list of objects of Element class (with Previous/Next references) and a header for first and last element, which is also an object of Element class. I would like to serialize the Queue. The question is - how to serialize a bidirectional linked list?
There is a lot of ways to do that. You can implement Serializable and take care about persisting all the objects. You can save all the data and relations in some structured XML. You can go with JSON.
The only problem can be if your Queue is generic (like the one in the standard library), you are going to have hard time saving an object of unknown type.
Related
I am working on the client end of an API that can perform searches on a variety of objects. All search functions return a list of objects like the below:
{
score : ...
object : {}
}
Score is how relative the result is and object is the object itself. What I'd like to be able to do is implement a Result<T> POJO that can handle the results for a variety of different objects using Jersey/MOXy but I am unsure as to how to do this (or if it's even possible). Thoughts?
I tried creating the Result object with a T item attribute, annotating it with #XmlAnyElement and unmarshalling using response.readEntity(new GenericType<List<Result<Object>>>(){}); but it always returned null.
Erm... turns out my approach was right after all. My objects weren't annotated with #XmlRootElement because it was not needed in other calls. This was leaving the objects as ElementNSImpl. So the answer to my question is basically in the question. Also had to add #XmlAnyElement(lax=true) to T attribute.
I used to understand a bunch of Java data structures but did not use it for a while. I am looking for two data structures.
the data structure that moves the position of the last retrieved element to the LAST position.
the data structure that moves the position of the last retrieved element
to the FIRST position.
I have tried to look for them on the Internet and saw e.g. LinkedList, ArrayList, HashMap, HashSet ect. They all provide the description and how to implement them but not the two points I mentioned above. Thus which are those two Java data structure?
See java.util.LinkedHashMap, from API: it is possible to create a linked hash map whose order of iteration is the order in which its entries were last accessed, from least-recently accessed to most-recently (access-order).
If you need a fixed-size data structure, please consider using the LRUMap from Apache Collections.
This is half an answer, though, since an LRUMap-like structure only accomplishes #2 of your requirements.
For #1, you need an MRUMap-like structure (MRU stands for most-recently-used). As a guide, refer to this LinkedHashMap-based implementation, whose drawback is that only the put() operation is considered as an access.
Hey im making a store for student details and i wanted some opinions on which collection to use. The store will have details such as name, number, address and email. The store will then be printed to a text file where i can load, save, edit and delete the details in the text file. I have never done this before and i do not no if there is any restrictions to file I/O when using collections. So i would really appreciate the comments. Thanks in advance.
If I were at your place,
then i would have created a bean class say Student and for collection ArrayList<Student> student = new ArrayList<Student>(); and as ArrayList is serialized so no issue for disk writing and a class for all IO operations.
For sorting ArrayList by object property look
Unless some special "fast location" capabilities are required, such as search by last name or by student ID, a list would be an appropriate collection to use.
List<Student> students = new ArrayList<Student>();
If you do need to organize your students by some attribute, say, by student ID, consider using LinkedHashMap:
Map<String,Student> studentById = new LinkedHashMap<String,Student>();
LinkedHashMap gives you a predictable order of iteration. You could use a regular HashMap<K,V>, but the order of iteration will be arbitrary. Finally, you could use a TreeMap<K,V>, which would base the order of iteration on the ordering of the keys.
Well if it has to be serializable, i.e. meaning you can write it to disk, you can use a List. Now before anyone screams you can't serialize a List that is correct, but you also cannot instantiate a List either. Since we know all known subclasses of List are serializable you can safely cast. In terms of how to store the data List<Student> should be just fine.
EDIT
There seems to be some confusion here. In Object Oriented languages we know that the is-a relationship holds true for objects specified in a hierarchy. So in the Java API we have an interface called List this interface has classes that implement it ArrayList for instance. This puts ArrayList in the hierarchy of List. Since ArrayList implements Serializable and we know that you cannot instantiate an object marked with the keyword interface (in Java). We can use casting to Serialize any known implementation of List. The reason why this will work is that the implementation (i.e. concrete object) that is passed around is guaranteed to be serializable.
In the simplest case a java.util.List will do exactly what you want. However, if you want to be able to find entries in the collection quickly ( to support your update requirements ), you should also probably look at java.util.Map. Map allows you to navigate quickly to a particular record without having to iterate over the entire collection, whereas with a List you'd have to look at every student in the collection in turn until you find the one you are interested in.
Here is a tricky data structure and data organization case.
I have an application that reads data from large files and produces objects of various types (e.g., Boolean, Integer, String) that are categorized in a few (less than a dozen) groups and then stored in a database.
Each object is currently stored in a single HashMap<String, Object> data structure. Each such HashMap corresponds to a single category (group). Each database record is built from the information in all the objects contained in all categories (HashMap data structures).
A requirement has appeared for checking whether subsequent records are "equivalent" in the number and type of columns, where equivalence must be verified across all maps by comparing the name (HashMap key) and the type (actual class) of each stored object.
I am looking for an efficient way of implementing this functionality, while maintaining the original object categorization, because listing objects by category in the fastest possible way is also a requirement.
An idea would be to just sort the keys (e.g., by replacing each HashMap with a TreeMap) and then walk over all maps. An alternative would be to just copy everything in a TreeMap for comparison purposes only.
What would be the most efficient way of implementing this functionality?
Also, if how would you go about finding the difference (i.e., the fields added and those removed), between successive records?
Create a meta SortedSet in which you store all the created maps.
Means SortedSet<Map<String,Object>> e.g. a TreeSet which as a custom Comparator<Map<String,Object>> which does check exactly your requirements of same number and names of keys and same object type per value.
You can then use the contains() method of this meta set structure to find out if a similar record does already exist.
==== EDIT ====
Since I've misundertood the relation between database records and the maps in the first place, I've to change some semantics my answer now of course a little bit.
Still I'would use the mentioned SortedSet<Map<String,Object>> but of course the Map<String,Object> would now point to that Map you and havexy suggested.
On the other hand could it be a step forward to use a Set<Set<KeyAndType>> or SortedSet<Set<KeyAndType>> where your KeyAndType will only contain the key and the type with appropriate Comparable implementation or equals with hashcode.
Why? You asked how to find the differences between two records? If each record relates to one of those inner Set<KeyAndType> you can easily use retainAll() to form the intersection of two successive Sets.
If you would compare this to the idea of a SortedSet<Map<String,Object>>, in both ways you would have the logic which differenciates between the fields within the comparator, one time comparing inner sets, one time comparing inner maps. And since this information gets lost when the surrounding set is constructed, it will be hard to get the differences between two records later on, if you do not have another reduced structure which is easy to use to find such differences. And since such a Set<KeyAndType> could act as key as well as as easy base for comparison between two records, it could be a good candidate to be used for both purposes.
If furthermore you wanna keep the relation between such a Set<KeyAndType> to your record or the group of Map<String,Object> your meta structure could be something like:
Map<Set<KeyAndType>,DatabaseRecord> or Map<Set<KeyAndType>,GroupOfMaps> implemented by a simple LinkedHashMap which allows simple iteration in original order.
One soln is to keep both category based HashMap and combined TreeMap. This will have slight more memory requirement, not much though, as you ll just keep the same reference in both of them.
So whenever you are adding/removing to HashMap you will do the same operation in the TreeMap too. This way both will always be in sync.
You can then use TreeMap for comparison, whether you want comparison of type of object or actual content comparison.
JAXB doesn't let you unmarshal already existing xml structures into HashMaps if they are not exactly the way JAXB expects them.
JAXB is fine with handling e.g. LinkedLists and filling them.
I was thinking of creating a interface with a getKey() method and a wrapper around the HashMap taking all objects that implement that interface. The wrapper can then use the getKey() method for all key related features of the map. The wrapper could then easily implement the Collection or List interface.
Because this idea doesn't seem to innovative to me I presume that it already exists in some package, but I'm not googling correctly for it... Can someone please name a good lib that can do this, or do I have to code this myself?
You might consider extending ForwardingList of guava, and using a HashMap in the back. I don't know of any implementation that will leave you only the actual mapping.
Another alternative is creating JAXB XmlAdapter to adapt the values to your map. I think this one is more appropriate.
If all you are trying to pass the information content of a Map as a Collection, use Map.entrySet(). That gives you a Set<Map.EntrySet<K,V>> object; i.e. a collection whose elements are the key/value pairs of the Map. To reconstruct a Map from the collection, you will need to iterate the set and perform an put for each element.