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.
Related
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.
I want to ask a question about Java. I have a user-defined object class, student, which have 2 data members, name and id. And in another class, I have to declare that object[], (e.g. student stu[?];). However, I don't know the size of the object array. Is it possible to declare an object array but don't know the size? thank you.
As you have probably figured out by now, regular arrays in Java are of fixed size (an array's size cannot be changed), so in order to add items dynamically to an array, you need a resizable array. In Java, resizable arrays are implemented as the ArrayList class (java.util.ArrayList).
A simple example of its use:
import java.util.ArrayList;
// Adds a student to the student array list.
ArrayList<Student> students = new ArrayList<Student>();
students.add(new Student());
The <Student> brackets (a feature called generics in Java) are optional; however, you should use them. Basically they restrict the type of object that you can store in the array list, so you don't end up storing String objects in an array full of Integer objects.
User ArrayList instead. It'll expand automatically as you add new elements. Later you can convert it to array, if you need.
As another option (not sure what exactly you want), you can declare Object[] field and not initialize it immediately.
Its not possible,we need to specify the size of array when declaring object array;
one way to declare object array
student st[];
st=new student[3];
second way
student st[]=new student[5];
in both cases not any objects are created only the space is allocated for the array.
st=new student[1];
this will create a new object;
You could declare as: Student stu[]=null;, and create it with fixed size: stu[]=new Student[10] until you could know the size. If you have to use array.
As part of an ongoing class project, we were asked to implement Maps for better object linking.
In short, we currently have four arraylists which hold objects
// Array Lists used for sorting.
private static ArrayList<Party> partyList = new ArrayList<Party>();
private static ArrayList<Creature> creatureList = new ArrayList<Creature>();
private static ArrayList<Treasure> treasureList = new ArrayList<Treasure>();
private static ArrayList<Artifact> artifactList = new ArrayList<Artifact>();
Each class has their own fields (ie, Party has "index","name", Creature has "index", "name", "age", height", etc...but they all have a unique index)
This week we are to implement hashmaps, where the key of an object, is its index.
so, as an exmaple:
creatureMap.put(creature.index, creature)
...
Our program also allows searching. So i understand that now when we search by an index, we just search the appropriate hashmap for the index we want, and work with the object that is its value.
However, our program also allows the user to search by name, height, weight, etc. So, how are hashmaps being used efficiently here if it only helps when searching by index? What happens if i want to search a creature by name? I would have to loop through every value in the hashmap, look at its 'name' field..which is exactly what i am doing with the arraylist.
Our professor said this when someone asked a similar question:
The idea is that in the first project, the simple approach was to
insert all items into array lists and when one needed to link a
creature to a party, or an item to a creature, one would have to
search the ArrayList linearly until the index of the item was found.
This is O(n) operation if the ArrayList is not sorted, and an O(log n)
operation if the list is sorted, but the sorting is typically O(n*n)
or O(n log n) depending on the sorting operation used.
This week, I am asking you to implement an O(1) searching system based
on a map data structure. Thus, we should use the index of a item as
its key to generate the links. This is used once during processing of
the input file.
Thus, I am not sure i am understanding the concept of Maps / key-value pairs correctly.
Your understanding is correct: if your key is an index, you can only use the map to efficiently lookup by index. If you wanted to search by name, then you would have to key on the name.
I'm not too sure on what your professor meant by this:
Thus, we should use the index of a item as its key to generate the links.
(I think he refers to linking objects by index, as in "link a creature to a party" - maybe he did not refer to the use of hashmaps for searching)
On a side note, it's good practice to declare variables based on interfaces rather than concrete types. In your example, you should define your list fields as List instead of ArrayList:
private static List<Party> partyList = new ArrayList<Party>();
Running through your questions (and statements) in order....
So i understand that now when we search by an index, we just search
the appropriate hashmap for the index we want, and work with the
object that is its value.
That is correct.
However, our program also allows the user to search by name, height, weight, etc. So, how are hashmaps being used efficiently here if it only helps when searching by index?
If your hashmap is only storing by index then you are correct that it does not help you search by any other field. You could create a map for those fields also, but I don't think that's what your professor want (see below)
What happens if i want to search a creature by name? I would have to loop through every value in the hashmap, look at its 'name' field..which is exactly what i am doing with the arraylist.
Yes, if you needed to search by name, then you would use the values() method and iterate through that, checking each item.
when one needed to link a creature to a party, or an item to a creature, one would have to search the ArrayList linearly until the index of the item was found
...
Thus, we should use the index of a item as its key to generate the links. This is used once during processing of the input file.
This suggests to me that there is another part of the assignment - something to do with reading input from a file, and linking parties, creatures and items together.
I assume that input file for the parties refers to the creatures by index (and likewise for the creatures referring to items).
It is that linkage that the professor wants you to speed up by using these hashmaps.
I don't think he is trying to get you to change the way other sorts of searching works
(Obviously this is a guess since I don't know what the assignment actually says)
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.
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.