How to store information about many people in Java - java

My problem is to store details of people in Java. I looked up at the Oracle website topic How to Use Tables and found out that one can use object arrays(2 dimensional) to store details.
But my interest is to make a dynamic object array so I can store any amount of data and also take input to store those details from the user. For instance, at the beginning of the program I can specify an object array to hold 5 records, but I actually want an array that could add another available location if I need to add more records (dynamic).
Is there a way this is possible in java ? If so, do you happen to know any good places I could start, perhaps a link. Is storing using an Object array the best option?

An array holds homogenous data, i.e. usually the class of everything in every cell of an array is the same. You will likely not want to store a person's name and his shoe size in fields of the same type, so... let's drop one of the array's dimensions. You should declare a class called something like Person and specify within it all the attributes you want to store for a person. Having done that, you will only be wanting to store a one dimensional array (or something) of Person.
Next, note that arrays are fixed in size. If you want to extend an array, you would need to allocate a new, bigger array, copy the contents of the old one into the new one and then go on working with the new one in place of the old one.
That's a lot of work, and error prone. In the modified words of Apple, there's a class for that! The older qualified class was Vector, a class where you could store objects and that would grow every time you add a new object to it. Nowadays, the class to use for this (it's a bit more efficient) is ArrayList. Same thing: You do
ArrayList<Person> myList = new ArrayList<Person>();
and then you can repeatedly
newPerson = new Person("Bruce", "Wayne", 1972, "Gotham City");
myList.add(newPerson);
and you can access folks in the list by doing
int personNumber = 0;
Person retrievedPerson = myList.get(personNumber);
or even
for (Person someone : myList) {
System.out.println(someone);
}
EDIT
OK, to store people with an ID and access them by that ID assuming the person ID is an integer, some appropriate code would be:
TreeMap<Integer, Person> myMap = new TreeMap<Integer, Person>();
newPerson = ...
myMap.put(newPerson.getId(), newPerson);
then you can retrieve it with
Person p = myMap.get(id);

Look at java.util.List, java.util.Map, and System.arraycopy for some data structures that will help you.

First you should understand that the Object array passed to the JTable won't get stored. It just be used to display the records of what you've done. To store the values you've got, you have to use Files or DB.
You can set Object array size dynamically in a way that you should know how many records you really need to show. I think with JDK 1.6 you can't dynamically change the size of the Array, but the upcoming JDK 7 may provide such a feature.

Related

is it possible to create a hash map where each value is a method that acts differently on an object

Problem
I want to know if this is possible if I could create a State machine that would contain all the methods and the Values of MethodById would be stated in the machine.
P.S. this is my first question ever on here. If I do it wrong I'm sorry but that is why.
Description (TL;DR)
I'm trying to cross reference data about Sales representatives. Each rep has territories specified by zip-codes.
One dataset has the reps, their territories and their company.
Another data set has their names, phone number and email.
I made a Sales-rep class that takes from the first data-set and needs to be updated with the second data-set.
I also need the Sales-reps to be put in a look-up table (I used a hashmap for this) of <key: zip code, value: Sales-rep object>.
What I want is for each Sales-rep object to having an ID that is standard across all my datasets. I can't use the data I'm provided with because it comes from many different sources and its impossible to standardize any data field.
Names, for example, are listed so many different ways it would be impossible to reconcile them and use that as an ID.
If I can get an ID like this (something like an SSN but less sensitive) then I want to try what my question is about.
I want to iterate through all the elements in my <key: zip code, value: Sales-rep object> hashmap, we will call it RepsByZipCode. When I iterate through each Salesrep object I want to get an ID that I can use in a different hashmap called MethodById <key: ID, value: a method run on the Object with this ID>.
I want it to run a different method for each key on the Object with the matching key (AKA the ID). The point is to run a different method on each different object in linear time so that by the end of the for loop, each object in RepsByZipCode will have some method run on it that can update information (thus completing the cross-referencing).
This also makes the code very extendable because I can change the method for each key if I want to update things differently. Ex:
//SalesRep Object Constructor:
SalesRep(String name, String email, ..., String Id)
Map<String zipcode, Salesrep rep> RepsByZipCode = new HashMap<>{}
//code fills in the above with the first dataset
Map<String ID, ??? method> MethodById = new HashMap<>{}
//code fills in the above with the second dataset
for(String ZipKey:RepsByZipCode){
Salesrep Rep = RepsByZipCode.get(ZipKey);
Rep.getId = ID;
MethodById.get(ID);
//each time this runs, one entry in RepsByZipCode is updated with one
//method from MethodById.
//after this for loop, all of RepsByZipCode has been updated in linear time
You could put these methods into different classes that implement a common interface, and store an instance of each class in your map. If you're using at least Java 8 and your methods are simple enough, you could use lambdas to avoid some boilerplate.

Java: Wrapping objects in some type of collection to store duplicates in a set

I want to make a set of some type of collection (not sure which one yet) as a way of "storing duplicates" in a set. For example if I wanted to add the integer 5 with 39 additional copies I could put it into an arraylist at index 39. Thus if I were to get the size of the arraylist, I would know how many copies of 5 existed within the set.
There are a few other ways I could implement this but I have yet to decide on one. The main issue I'm having with implementing this is that I'm not sure how I can "dynamically" make arraylists (or whatever collection I may end up using) so that whenever someone were to call mySet.add(object), the object is first inserted into a unique arraylist then into the set itself.
Can anyone give me some ideas on how I could approach this?
EDIT:
Sorry I should have been more clear in my question. The point of the code that I'm writing is that we have a set-like collection that allows duplicates. And yes some of the associated methods will be re-written/will have to be re-written. Also my code should be written under the assumption that we do not know what type of object is being inserted(only one data type per set though) nor how many instances of the same object will be added nor how many different unique objects will be added.
I would rather go for using a Map like
HashMap list <Object, Integer>
where Object is the Object that you want to count and Integer is the count
You could try guava's MultiSet, I think it's what you want.
It can store the count of each object. What you need to do is just
multiSet.put(object);
And if it is put for the first time, like you said, a new list will be created, or its count will added by one.

Making a java phone book using the link list data structure?

I got an assignment in which I have to make a phone book using a link list.
In this list I got to be able to add an entry. The entry must have a person first name,last name and phone number.
I have to be able to delete the first,last, and phone number of the entries.
How can I do this I am think of creating a class named entry with string for first,last,and phone number.
And when the user decides to create a new Record put a new Object entry with these fields. Into the link list.
The problem is how can I create a new Object and name it when the user want to put it on the list.
I cannot keep using the same name for an object over and over or can I?
You can't.
Suppose you have a class, Person, with properties as you suggested. directory is an object of type LinkedList<Person>. The correct way to do what you are trying to do is to make Person immutable. Every time you want to add a Person, you write statements such as directory.add(new Person("George", "Washington", "1776")) (the constructor initializes final Strings.
You must make new objects because LinkedList only stores references to objects, not copies of them.
Really, though, you can instead of Person use an associative array, for example mapping enum types for properties to strings.
Make a list of some kind (array, ArrayList, whatever floats your boat) and store it there using new Record(...).
Making a class for keeping the data is a good way to solve the problem.

Java creating a roster of unknown size

I'm posting this as a pick your brain kind of question. Is an array the appropriate type of data holder for a roster of unknown size?
I am looking to create a small class with 3 methods
addToRoster //which would add a name to the proposed Array taking in an array and a String.
getRoster //which would return the elements of the roster printed to the console.
remFrRoster // which would take a name, cycle through the roster and remove it if found.
I'm really a beginner at Java. I've only been programming about a week and looking to find out a few things. One, is this an appropriate design methodology for a class? Two, are arrays the preferred method for storing a roster of Strings? Lastly, do i have to initialize my array to a definite size or can i have it change size as it approaches the limits of the size it is initialized to?
thanks,
pano
You could use an ArrayList:
ArrayList<Player> roster = new ArrayList<Player>();
roster.add(new Player(32));
System.out.println(roster.get(0).getAge());
An ArrayList is essentially the same thing as an array, but it's size can be changed. Only use an ArrayList if the number of players on the roster is going to change while the program is running. i.e. If you are going to read the players in from a file just use an array, but if you are going to create an indeterminate amount of players after the program has started, use an ArrayList.
I would use a Collection instead of an array to dynamically resize the store based on the number of elements.
A List would be appropriate to store arbitrary number of elements.
A Map would be appropriate to store arbitrary number of objects keyed using an attribute of the object.
If your Roster happens to contains attributes other than the Name, then you can use a Map to store your Roster objects.
addToRoster would simply put an element in the Map as map.put(roster.getName(), roster).
getRoster would iterate through the map.values() collection and prints each roster object.
remFrRoster would simply removes the roster object using the name specified, map.remove(name). If the return value from this call is null, it means there is no roster object with that name.
HTH.

Difference between HashMap and ArrayList in Java?

In Java, ArrayList and HashMap are used as collections. But I couldn't understand in which situations we should use ArrayList and which times to use HashMap. What is the major difference between both of them?
You are asking specifically about ArrayList and HashMap, but I think to fully understand what is going on you have to understand the Collections framework. So an ArrayList implements the List interface and a HashMap implements the Map interface. So the real question is when do you want to use a List and when do you want to use a Map. This is where the Java API documentation helps a lot.
List:
An ordered collection (also known as a
sequence). The user of this interface
has precise control over where in the
list each element is inserted. The
user can access elements by their
integer index (position in the list),
and search for elements in the list.
Map:
An object that maps keys to values. A
map cannot contain duplicate keys;
each key can map to at most one value.
So as other answers have discussed, the list interface (ArrayList) is an ordered collection of objects that you access using an index, much like an array (well in the case of ArrayList, as the name suggests, it is just an array in the background, but a lot of the details of dealing with the array are handled for you). You would use an ArrayList when you want to keep things in sorted order (the order they are added, or indeed the position within the list that you specify when you add the object).
A Map on the other hand takes one object and uses that as a key (index) to another object (the value). So lets say you have objects which have unique IDs, and you know you are going to want to access these objects by ID at some point, the Map will make this very easy on you (and quicker/more efficient). The HashMap implementation uses the hash value of the key object to locate where it is stored, so there is no guarentee of the order of the values anymore. There are however other classes in the Java API that can provide this, e.g. LinkedHashMap, which as well as using a hash table to store the key/value pairs, also maintains a List (LinkedList) of the keys in the order they were added, so you can always access the items again in the order they were added (if needed).
If you use an ArrayList, you have to access the elements with an index (int type). With a HashMap, you can access them by an index of another type (for example, a String)
HashMap<String, Book> books = new HashMap<String, Book>();
// String is the type of the index (the key)
// and Book is the type of the elements (the values)
// Like with an arraylist: ArrayList<Book> books = ...;
// Now you have to store the elements with a string key:
books.put("Harry Potter III", new Book("JK Rownling", 456, "Harry Potter"));
// Now you can access the elements by using a String index
Book book = books.get("Harry Potter III");
This is impossible (or much more difficult) with an ArrayList. The only good way to access elements in an ArrayList is by getting the elements by their index-number.
So, this means that with a HashMap you can use every type of key you want.
Another helpful example is in a game: you have a set of images, and you want to flip them. So, you write a image-flip method, and then store the flipped results:
HashMap<BufferedImage, BufferedImage> flipped = new HashMap<BufferedImage, BufferedImage>();
BufferedImage player = ...; // On this image the player walks to the left.
BufferedImage flippedPlayer = flip(player); // On this image the player walks to the right.
flipped.put(player, flippedPlayer);
// Now you can access the flipped instance by doing this:
flipped.get(player);
You flipped player once, and then store it. You can access a BufferedImage with a BufferedImage as key-type for the HashMap.
I hope you understand my second example.
Not really a Java specific question. It seems you need a "primer" on data structures. Try googling "What data structure should you use"
Try this link http://www.devx.com/tips/Tip/14639
From the link :
Following are some tips for matching the most commonly used data structures with particular needs.
When to use a Hashtable?
A hashtable, or similar data structures, are good candidates if the stored data is to be accessed in the form of key-value pairs. For instance, if you were fetching the name of an employee, the result can be returned in the form of a hashtable as a (name, value) pair. However, if you were to return names of multiple employees, returning a hashtable directly would not be a good idea. Remember that the keys have to be unique or your previous value(s) will get overwritten.
When to use a List or Vector?
This is a good option when you desire sequential or even random access. Also, if data size is unknown initially, and/or is going to grow dynamically, it would be appropriate to use a List or Vector. For instance, to store the results of a JDBC ResultSet, you can use the java.util.LinkedList. Whereas, if you are looking for a resizable array, use the java.util.ArrayList class.
When to use Arrays?
Never underestimate arrays. Most of the time, when we have to use a list of objects, we tend to think about using vectors or lists. However, if the size of collection is already known and is not going to change, an array can be considered as the potential data structure. It's faster to access elements of an array than a vector or a list. That's obvious, because all you need is an index. There's no overhead of an additional get method call.
4.Combinations
Sometimes, it may be best to use a combination of the above approaches. For example, you could use a list of hashtables to suit a particular need.
Set Classes
And from JDK 1.2 onwards, you also have set classes like java.util.TreeSet, which is useful for sorted sets that do not have duplicates. One of the best things about these classes is they all abide by certain interface so that you don't really have to worry about the specifics. For e.g., take a look at the following code.
// ...
List list = new ArrayList();
list.add(
Use a list for an ordered collection of just values. For example, you might have a list of files to process.
Use a map for a (usually unordered) mapping from key to value. For example, you might have a map from a user ID to the details of that user, so you can efficiently find the details given just the ID. (You could implement the Map interface by just storing a list of keys and a list of values, but generally there'll be a more efficient implementation - HashMap uses a hash table internally to get amortised O(1) key lookup, for example.)
A Map vs a List.
In a Map, you have key/value pairs. To access a value you need to know the key. There is a relationship that exists between the key and the value that persists and is not arbitrary. They are related somehow. Example: A persons DNA is unique (the key) and a persons name (the value) or a persons SSN (the key) and a persons name (the value) there is a strong relationship.
In a List, all you have are values (a persons name), and to access it you need to know its position in the list (index) to access it. But there is no permanent relationship between the position of the value in the list and its index, it is arbitrary.

Categories