Another way to store a collection of items is called a keyed bag. In this type o
ID: 3650687 • Letter: A
Question
Another way to store a collection of items is called a keyed bag. In this type of bag, whenever an item is added, the programmer using the bag also provides an integer called the key. Each item added to the keyed bag must have a unique key; twp items cannot have the same key. For this project, implement, a keyed bag in which the items to be stored are strings (perhaps people's names) and the keys are numbers (perhaps Social Security or other identification numbers). So, the insertion method has this specification:public void insert
(String entry, int key);
// Precondition: size() < CAPACITY, and the
// bag does not yet contain any item
// with the given key.
// Postcondition: A new copy of entry has
// been added to the bag, with the given key.
When the programmer wants to remove or retrieve an item from a keyed bag, the key of the item must be specified rather than the item itself. The keyed bag should also have a Boolean method that can be used to determine whether the bag has an item with a specified key. A keyed bag differs from the bag with receipts. In a keyed bag, the programmer using the class specifies a particular key when an item is inserted. In contrast, for a bag with receipts, the insert method returns a receipt, and the programmer using the class has no control over what that receipt might be. Here's an implementation idea: A keyed bag can have two private arrays, one that holds the string data and one that holds the corresponding keys. The data at location data[i] has a key that is stored in key [i].
Explanation / Answer
There can be many ways to implement them. You can use HashMap in Java which store key value pairs. Or you can use simple array method you have described above (using data[i] and location[i]). One more lucid method can be - String data[200][2]; where String[0][i] would store the key for element i, and String[1][i] would store the data element.
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.