Best collection to store student details? - java

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.

Related

How to associate an object with the quantity of that object

I am working on a Java application and came across a general implementation/meta question and wanted to reach out for suggestions.
I am looking to associate a Java object with a quantity. The java object is complex. In my case, it is a serializable object that represents JSON data from a 3rd party API. I am looking to associate a quantity with this complex Java object.
As this may be something that is easier to understand with an example, here is one. Say I have a Car class that is used to represent a car. It contains all the details of what make a car a car and is a general form that can be used to communicate over an API. Say I am making an inventory app for a dealership. The dealership would want to know how many of each Car they have. Hence the need for the association.
Ideas
There are some ways I can think of the do this.
Class it out
One idea would be to create classes that capture this association. One could have an InventoryEntry class that contains a Car and a quantity. Your dealerships inventory would then consist of a List of InventoryEntry objects.
Arrays
One can also implement this association via an Array mechanism. This can be done by creating an ArrayList<Car> for the cars and an ArrayList<Integer> for the quantity. The index for each list would be used to associate the two.
Would you recommend one of these method or some other implementation?
Using ArrayList makes it a little bit easier to start out, but if you are going to maintaining and extending this application, creating a custom class will save you a lot of time in the long run. The reason is that it would be difficult to change the ArrayList class. Yes, you could subclass the arraylist class, and override the methods that you need to, but that is making more work for yourself.
For the basic scenario that you gave, creating a CarInventory class could be extended for new behavior. The new class could just wrap a basic ArrayList or HashMap implementation, but being able to extend your application for long term maintainability is important.

Optimization support for list in android

I have small issue in arraylist android, let me tell you where i'm facing the issue.
I have a custom contact object, which holds the details about name, contact number and a unique ID. when i query the database i get the list and i will be storing in an ArrayList.
Here how i do
Arraylist<contact> ctlist = new Arraylist(contact);
ctlist = getitemfromDB();
in the next scenario, i do query and get some set of contact object based on certain condition. i get
again contact list objects.
Arraylist<contact> newctlist = new Arraylist(contact);
newctlist = getitemfromDB(condition);
Now, if i pick any object from newctlist and search in ctlist, though the object is present in ctlist
compiler says object not found.
may i know what is wrong with the above way, if i search inside same list i.e if i pick an object from newctlist and search in it, i will get correct expected result.
what would be the problem.
As told by Mitch Wheat, you are trying to compare two different objects. That's because List uses equals method to retrieve specific object. I think you didn't override it in your custom class.
Just implement equals and hashCode methods based on fields in your contact class.
In fact, you should try to always override equals and hashCode methods in classes where equality have a different meaning than just reference equality, e.g. beans. Please have a look there and there. Moreover, if you can, read chapter three from Josh Bloch's "Effective Java" which contains quality rules for those implementations (By the way, read the whole book, it's great).
Please note that there are librairies helping you implementing correctly those (Java7 java.util.Objects, Guava Objects, apache commons EqualsBuilder and HashCodeBuilder)
Be careful as those methods must have very precise mathematical property

Permanent collections in Java

According to my assignment which asks to develop a small-scale Student Accommodation Management System :
The application should be developed using object-oriented concepts using Student class and Apartment class, implementing the appropriate data fields and methods for the classes. Data may be stored in collections i.e. array of objects, vectors, etc. or into data files except a database.
So far, I have worked with Sets. I am not sure if it the right way but I added HashSets to my classes. Example:
public static Set<Apartment> listOfApartments = new HashSet<Apartment>();
// in Apartment Class)
Now that I just realized I actually need persistent collections or some solutions to actually store the data permanently.
Any Suggestions?
If I where you I would use something such as an ArrayList to store data, especially students. Sets do not allow duplicate data so this could cause problems down the line.
With regards to persisting your data, you should take a look at the ObjectOutputStream to store your objects and to the ObjectInputStream to load them back into your application. You can take a look here for an ObjectStreams tutorial.
What I would recommend though is to use something such as XStream (you can see how to use it here). This will allow your application to store data in a human readable way (which is helpful for debugging) and will also allow your data to be read by different programming languages.
If Appartment is Serializable, then Set<Apartment> is also Serializable and doens't require any extra work to persist it using java.io classes
To make a class Serializable, you must :
make it implement the interface java.io.Serializable
add a default constructor
It is that easy

Best Place to Put a Comparator

I am sorry if I am asking something that has been answered already but I could not find a reference. My question is where is the best place to put a comparator which layer does it belong to.For example I need a list of User Objects sorted by users date of birth then surname and then first name.
If the comparator is intrinsic to the object (e.g. it's the only way of ordering it that makes sense), then I would just implement Comparable on the object.
If the comparator is one of many (e.g. a Comparator instance), and only makes sense in a particular context, then I'd place the comparator class in that layer.
In your case if would put it on the domain class and sort it in the dao during fetch meaning have two methods(or more based on Comaprision types) on dao one to just get a list of unsorted object e.g. getUsers() and one method for sorted list e.g getSortedUers(); ofcourse you can only have a sorted method but always calling a sort is an over head if no sort is required.
If you are using database, then best way is to sort it in query itself, using order by
The general answer would be: put it where it is most required :-)
This depends a lot on your actual design and architecture. In general, either you can put it next to your user object, or into the layer which uses it most (or exclusively).
Yeah, if you use database or some external service and it's possible to sort there it's best way. But if you need to sort objects in your application it depends on your architecture. There are 2 variants. If you need sort only once - create anonymous class then you won't store reference on this object. If you need to make sort several times you can store it as static field of class or a non-static field.

structure for holding data in this instance (Hashmap/ArrayList etc)?

Best way to describe this is explain the situation.
Imagine I have a factory that produces chairs. Now the factory is split into 5 sections. A chair can be made fully in one area or over a number of areas. The makers of the chairs add attributes of the chair to a chair object. At the end of the day these objects are collected by my imaginary program and added into X datatype(ArrayList etc).
When a chair is added it must check if the chair already exists and if so not replace the existing chair but append this chairs attributes to it(Dont worry about this part, Ive got this covered)
So basically I want a structure than I can easily check if an object exists if not just straight up insert it, else perform the append. So I need to find the chair matching a certain unique ID. Kind of like a set. Except its not matching the same object, if a chair is made in three areas it will be three distinct objects - in real life they all reperesent the same object though - yet I only want one object that will hold the entire attribute contents of all the chairs.
Once its collected and performed the update on all areas of the factory it needs iterate over each object and add its contents to a DB. Again dont worrk about adding to the DB etc thats covered.
I just want to know what the best data structure in Java would be to match this spec.
Thank you in advance.
I'd say a HashMap: it lets you quickly check whether an object exists with a given unique ID, and retrieve that object if it does exist in the collection. Then it's simply a matter of performing your merge function to add attributes to the object that is already in the collection.
Unlike most other collections (ArrayList, e.g.), HashMaps are actually optimized for looking something up by a unique ID, and it will be just as fast at doing this regardless of how many objects you have in your collection.
This answer originally made reference to the Hashtable class, but after further research (and some good comments), I discovered that you're always better off using a HashMap. If you need synchronization, you can call Collections.synchronizedMap() on it. See here for more information.
I'd say use ArrayList. Override the hashcode/equals() method on your Chair object to use the unique ID. That way you can just use list.contains(chair) to check if it exists.
I'd say use an EnumMap. Define an enum of all possible part categories, so you can query the EnumMap for which part is missing
public enum Category {
SEAT,REST,LEGS,CUSHION
}

Categories