This question already has answers here:
Java Printing Functions
(2 answers)
Closed 9 years ago.
I need help with these two functions print and printall which really do what the title of the functions says
// Prints a directory of all StockItems with their associated
// price, in sorted order (ordered by SKU).
public void printAll() {
}
// Prints a directory of all StockItems from the given vendor,
// in sorted order (ordered by SKU).
public void print(String vendor) {
}
Here is the full function below. DictionaryADT is a class that is used in implementing Hashtables and BST. The DictionaryADT just consists of functions. It has NOTHING to do with Map.
import data_structures.*;
import java.util.Iterator;
import java.util.Map;
public class ProductLookup {
DictionaryADT<String,StockItem> dictionary;
private int maxSize;
public ProductLookup(int maxSize, DictionaryADT<String,StockItem> dictionary) {
this(maxSize);
this.dictionary = dictionary;
}
// Constructor. There is no argument-less constructor, or default size
public ProductLookup(int maxSize) {
this.maxSize = maxSize;
}
// Adds a new StockItem to the dictionary
public void addItem(String SKU, StockItem item) {
dictionary.insert(SKU,item);
}
// Returns the StockItem associated with the given SKU, if it is
// in the ProductLookup, null if it is not.
public StockItem getItem(String SKU) {
if (SKU == null)
return null;
return dictionary.getValue(SKU);
}
// Returns the retail price associated with the given SKU value.
// -.01 if the item is not in the dictionary
public float getRetail(String SKU) {
if (!dictionary.contains(SKU))
return (float) -.01;
return getItem(SKU).getRetail();
}
public float getCost(String SKU) {
if (!dictionary.contains(SKU))
return (float) -.01;
return getItem(SKU).getCost();
}
// Returns the description of the item, null if not in the dictionary.
public String getDescription(String SKU) {
if (!dictionary.contains(SKU))
return null;
return getItem(SKU).getDescription();
}
// Deletes the StockItem associated with the SKU if it is
// in the ProductLookup. Returns true if it was found and
// deleted, otherwise false.
public boolean deleteItem(String SKU) {
if (SKU == null)
return false;
return dictionary.remove(SKU);
}
// Prints a directory of all StockItems with their associated
// price, in sorted order (ordered by SKU).
public void printAll() {
}
// Prints a directory of all StockItems from the given vendor,
// in sorted order (ordered by SKU).
public void print(String vendor) {
}
// An iterator of the SKU keys.
public Iterator<String> keys() {
return dictionary.keys();
}
// An iterator of the StockItem values.
public Iterator<StockItem> values() {
return dictionary.values();
}
}
Unfortunately it seems like java's Iterator cannot be sorted using built in functions as it is not a collection. You can, however, convert it to a List first, and then sort.
// Prints a directory of all StockItems with their associated
// price, in sorted order (ordered by SKU).
public void printAll() {
// Convert the iterator of SKU's to a List
List SKUList = new ArrayList();
Iterator<String> keyIt = dictionary.keys();
while( keyIt.hasNext() )
SKUList.add(it.next());
// Sort the SKU's
Collections.sort(SKUList);
// Print each item
for(int i=0; i<SKUList.size(); i++){
StockItem item = dictionary.getValue( SKUList.get(i) );
// Print what you want here
}
}
Related
This is my assignment, I'm working on the step 3:
I need to implement a method called getItems() that takes a boolean value and returns a new ArrayList with items having the property that match the given value.
So far When I print it out it just shows the whole list in the array list, not only the objects having true property.
My code:
import java.util.ArrayList;
public class Shoppinglist9_6_pt2 {
ArrayList<Item> shoppingList = new ArrayList<>();
public Shoppinglist9_6_pt2(ArrayList<Item> shoppingList) {
this.shoppingList = shoppingList;
}
public void showList() {
for ( Item item : shoppingList){
System.out.printf("\nItem:%s Ct:%s", item.getName(),
item.getCt());
}
}
public ArrayList<Item> getItems(boolean gotIt) {
gotIt = true;
for (Item item : shoppingList){
if(item.getGotIt() == gotIt){
showList();
}else{
gotIt = false;
}
}
// Todo: return an ArrayList of item that
// match the gotIt true or false value.
// For example if set to True, then return
// an ArrayList of Item with gotIt=True.
return new ArrayList<Item>();
}}
public class Item {
private String name;
private int ct;
private boolean gotIt;
}
public Item(String name, int ct,boolean gotIt) {
this.name = name;
this.ct = ct;
this.gotIt = gotIt;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCt() {
return ct;
}
public void setCt(int ct) {
this.ct = ct;
}
public boolean getGotIt(){
return gotIt;
}
public void setGotIt(boolean gotIt) {
this.gotIt = gotIt;
}
#Override
public String toString() {
return "Item :" +
"name='" + name + '\'' +
", ct=" + ct +
"Got it=" + gotIt;
}
}
This is my main:
public class inClass_Shopping_9_6_pt2 {
public static void main(String[] args) {
Shoppinglist9_6_pt2 sl = new Shoppinglist9_6_pt2();
sl.addItem( "Banana", 6,true);
sl.addItem("Coconut", 2,false);
sl.addItem("Apple", 12,true);
sl.getItems(true);
}
}
Also, you might observe the method gotIt() is grayed out & says parameters can be converted to a local varaible, same with the return. 'Item' in ArrayList<Items> is grayed out and says explicit type argument item can be replaced with <>, but this is the template my professor had sent us, and we need to follow it.
You have the new instance variable, you have the getters and setters, just the getItems method does not yet do the job...
You want to get a list with all the entries of the shopping list that have the attribute gotIt either true or false depending on the gotIt variable. How can you use the gotIt variable to get all the items you want?
Normally one would choose different names for the parameter of getItems, so it doesn't collide with the attributes name
You need to perform the following steps:
create a new ArrayList.
iterate through the sopping list and add each item with gotIt property matches the provided boolean value into the newly created ArrayList.
return the list.
That's how it might look like:
public ArrayList<Item> getItems(boolean gotIt) {
ArrayList<Item> items = new ArrayList<>();
for (Item item : shoppingList) {
if (item.getGotIt() == gotIt) {
items.add(item);
}
}
return items;
}
Note: although according to the assignment requirements you have to use ArrayList as a type in your code, it's not good practice to make the code dependent on concrete implementations. See What does it mean to "program to an interface"?
I know I have join party late, and my answer is not different from Alexandar.
I'm not offering a lot of assistance, still you can try using lambdas.
For instance
public ArrayList<Item> getItems(boolean gotIt) {
ArrayList<Item> items = new ArrayList<>();
shoppingList.forEach(item -> {
if(item.getGotIt() == gotIt) items.add(item);
});
return items;
}
For print,
sl.getItems(false).forEach(System.out::println);
I have a task where i have to create a recently used list in java. I'm a bit lost and I do not really know where to start. Please help! This is the code I have been given to start with:
public class RecentlyUsedList {
// Members (a.k.a. fields)
private String[] theItems;
private int noOfItems;
// Constructor
public RecentlyUsedList(int capacity) {
// Create the array with indicated capacity
// Initialize numberOfItems
}
// Public methods
public int getNoOfItems() {
}
public boolean isEmpty() {
// Is this list empty or not?
}
public String getItemAt(int index) {
// If index is out of range, return null
// Otherwise return a reference to the indicated item
}
public void addItem(String item) {
// 1. Check if the list contains this item; if so, remove it and pack
// 2. Check if the array needs resizing
// 3. Add the item to the list. Increment noOfItems.
}
public void removeItem(String item) {
// Check if the list contains this item; if so, remove it and call pack
// NB! use equals to compare Strings, e.g. str1.equals(str2)
}
public String toString() {
// Return a string of the form
// [1st item; 2nd item; ...]
}
// Private (helper) methods
private void pack(int index) {
// In a loop, starting at "index", copy item at position+1 to position
// (if the items are stored in "reverse order")
// Decrement noOfItems.
}
private void resize() {
// Create a new, temporary, reference and a corresponding String-array
// Copy all item-references to the new array
// Let the "theList" reference the new array (i.e. theItems = temp)
}
}
Please does anyone have directions on how to start?
Giving you a head start by giving code for 3 methods. Rest you can attempt on your own.
// Public methods
public int getNoOfItems() {
return noOfItems;
}
public String getItemAt(int index) {
if (index >= noOfItems) {
return null;
} else {
return theItems[index];
}
}
public String toString() {
StringBuilder builder = new StringBuilder("[");
for (int i = 0; i < theItems.length; i++) {
if (theItems[i] != null) {
builder.append(theItems[i]).append(";");
}
builder.append("]");
return builder.toString();
}
I'm using java 1.6.
I have a set of items, and each item has a name and a set of components. each component also has a name.
Set<Item>
Class Item
String name
Set<Component>
Class Component
String name
I'm now tasked with writing a method with input: item name + component name, and output: does this pair exist in the list of items.
public boolean hasItemComponentPair(String itemName, String componentName)
{
for(Item item : getItems())
{
if (item.getName() == itemName)
{
for(Component component : item.getComponents())
{
if (component.getName() == componentName)
{
return true;
}
}
}
}
return false;
}
The easiest way to do is by simply going through the elements of the sets one-by-one, and break if a match is found. This approach is doable for small sets.
My set of items is typically between 5 and 20 items, and the set of components is about the same. So there's between 25 and 400 unique item-component pairs. This amount of pairs seems too large for the naive algorithm to be efficient, especially if the method is called several times. But I also think a divide and conquer technique is too verbose for the given amount of elements.
What data structures and algorithms are typically used for this problem, keeping in mind the giving size of the sets?
If you can change your Item class you can do it like that:
class Item {
String name;
Map<String, Component> components;
}
In the map above key is the name of component.
Than change your code to:
public boolean hasItemComponentPair(String itemName, String componentName)
{
for(Item item : getItems())
{
if (item.getName().equals(itemName))
{
return item.getComponents().containsKey(componentName);
}
}
return false;
}
Now you need to traverse only one collection.
1) Sort the lists and do binary search on them.
2) Build indexes (typically as hashtable).
Override the equals and hashCode method in your Item and Component classes like following:
// Item.java
import java.util.Set;
public class Item
{
private String name;
private Set<Component> components;
public Item(String name)
{
this.name = name;
}
#Override
public int hashCode()
{
return name.hashCode();
}
#Override
public boolean equals(Object obj)
{
if (obj instanceof Item)
{
Item item = (Item) obj;
if (item.name != null && this.name != null)
return item.name.equals(this.name);
}
return false;
}
public Set<Component> getComponents()
{
return components;
}
public void setComponents(Set<Component> components)
{
this.components = components;
}
}
// Component.java
public class Component
{
private String name;
public Component(String name)
{
this.name = name;
}
#Override
public int hashCode()
{
return name.hashCode();
}
#Override
public boolean equals(Object obj)
{
if (obj instanceof Component)
{
Component component = (Component) obj;
if (component.name != null && name != null)
return component.name.equals(this.name);
}
return false;
}
}
This will give you constant time lookup. So you can search for elements in constant time.
Following is a demonstration:
import java.util.HashSet;
public class SearchDemo
{
public static void main(String[] args)
{
Item item1 = new Item("Item 1");
item1.setComponents(new HashSet<Component>());
item1.getComponents().add(new Component("Component A"));
item1.getComponents().add(new Component("Component B"));
item1.getComponents().add(new Component("Component C"));
Item item2 = new Item("Item 2");
item2.setComponents(new HashSet<Component>());
item2.getComponents().add(new Component("Component X"));
item2.getComponents().add(new Component("Component Y"));
item2.getComponents().add(new Component("Component Z"));
HashSet<Item> items = new HashSet<>();
items.add(item1);
items.add(item2);
// Input from user
String inputItem = "Item 2";
String inputComponent = "Component Y";
// Cast it to item and component
Item searchItem = new Item(inputItem);
Component searchComponent = new Component(inputComponent);
if (items.contains(searchItem)) // Constant time search
{
System.out.println("Contains Item");
for (Item item : items)
{
if (item.equals(searchItem))
{
if (item.getComponents().contains(searchComponent)) // Constant time search
{
System.out.println("Contains even the component");
}
}
}
}
}
}
The only issue is the for loop in the above lookup.
The item can be searched in constant time, but it has to be searched for again in the set (if it really exists) because I kind of fooled the program into believing that the searchItem is equal to the item in the set. Once the item is really found and its component set is extracted from it, its a constant time search for the componentItem.
If you have a HashMap of Components in the Item class, instead of the Set, and each key in the HashMap is the name of the component, then the input from the user can be searched in constant time!
I am trying to add data to my hashmap if the key does not already exist in the map. For some reason, even if the key does exist, the hashmap adds it anyways. I have no idea why this is happening. My addEntity method is the problem. I am trying to detect of the key is already in the hashmap, and if it is, then do nothing. However, it for some reason will always add the key, no matter if the key already exists.
My data file:
package timeTraveler.mechanics;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import net.minecraft.entity.EntityLiving;
public class PathingData
{
/**
* Entity data array
*/
public static Map<String[], List<int[]>> allEntityData;
public PathingData()
{
allEntityData = new HashMap<String[], List<int[]>>();
}
/**
* Adds an entity UUID (Unique ID)and MobType to the entity data ArrayList. If the entity already exists inside of the ArrayList, then it skips it.
* #param uuid
*/
public void addEntity(String[] entityData)
{
System.out.println(entityData[0]);
if(!allEntityData.containsKey(entityData))
{
System.out.println("Adding entity!");
allEntityData.put(entityData, new ArrayList<int[]>());
}
else
{
System.out.println("ENTITY ALREADY EXISTS IN ARRAY");
}
}
/**
* Adds data (X, Y, and Z) to the corresponding UUID (Unique ID) for the entity. If the entity's UUID does not exist, then it prints out a line that says the UUID cannot be found.
* #param uuid
* #param data
*/
public void addData(String[] entityData, String data)
{
System.out.println(entityData[0]);
if(allEntityData.containsKey(entityData))
{
System.out.println("Adding data to entity!");
int[] rawData = new int[3];
String[] pureData = data.split(",");
rawData[0] = Integer.parseInt(pureData[0]);
rawData[1] = Integer.parseInt(pureData[1]);
rawData[2] = Integer.parseInt(pureData[2]);
List<int[]> entityLocData = allEntityData.get(entityData);
entityLocData.add(rawData);
allEntityData.put(entityData, entityLocData);
}
else
{
System.out.println("ENTITY DOES NOT EXIST IN ARRAY! :(");
//addEntity(entityData);
}
}
/**
* Gets the data for a specific UUID (Unique ID) for an entity.
* #param uuid
* #return
*/
public List<int[]> getDataForUUID(String[] entityData)
{
List<int[]> entityLoc = allEntityData.get(entityData);
return entityLoc;
}
/**
* Clears all entities and their corresponding data from the map.
*/
public void clearAllEntitiesAndData()
{
allEntityData.clear();
}
/**
* Checks if entity exists inside of array
* #param uuid
* #return
*/
public boolean doesEntityExist(String[] entityData)
{
List<int[]> entityLoc = allEntityData.get(entityData);
if(entityData != null)
{
return true;
}
return false;
}
}
I have made sure that there is only one instance of the variable, and I always refer to that one variable in my .addEntity and .addData. Any ideas?
EDIT: I have just now tried to implement the suggestion proposed. However, it still just prints out the same thing, with timetraveler.core.StringArrayHolder#0 instead of the array. Here is the modified code:
package timeTraveler.mechanics;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import timeTraveler.core.StringArrayHolder;
import net.minecraft.entity.EntityLiving;
public class PathingData
{
/**
* Entity data array
*/
public static Map<StringArrayHolder, List<int[]>> allEntityData;
public PathingData()
{
allEntityData = new HashMap<StringArrayHolder, List<int[]>>();
}
/**
* Adds an entity UUID (Unique ID)and MobType to the entity data ArrayList. If the entity already exists inside of the ArrayList, then it skips it.
* #param uuid
*/
public void addEntity(StringArrayHolder entityData)
{
System.out.println(entityData);
if(!allEntityData.containsKey(entityData))
{
System.out.println("Adding entity!");
allEntityData.put(entityData, new ArrayList<int[]>());
}
else
{
System.out.println("ENTITY ALREADY EXISTS IN ARRAY");
}
}
/**
* Adds data (X, Y, and Z) to the corresponding UUID (Unique ID) for the entity. If the entity's UUID does not exist, then it prints out a line that says the UUID cannot be found.
* #param uuid
* #param data
*/
public void addData(StringArrayHolder entityData, String data)
{
System.out.println(entityData);
if(allEntityData.containsKey(entityData))
{
System.out.println("Adding data to entity!");
int[] rawData = new int[3];
String[] pureData = data.split(",");
rawData[0] = Integer.parseInt(pureData[0]);
rawData[1] = Integer.parseInt(pureData[1]);
rawData[2] = Integer.parseInt(pureData[2]);
List<int[]> entityLocData = allEntityData.get(entityData);
entityLocData.add(rawData);
allEntityData.put(entityData, entityLocData);
}
else
{
System.out.println("ENTITY DOES NOT EXIST IN ARRAY! :(");
//addEntity(entityData);
}
}
/**
* Gets the data for a specific UUID (Unique ID) for an entity.
* #param uuid
* #return
*/
public List<int[]> getDataForUUID(StringArrayHolder entityData)
{
List<int[]> entityLoc = allEntityData.get(entityData);
return entityLoc;
}
/**
* Clears all entities and their corresponding data from the map.
*/
public void clearAllEntitiesAndData()
{
allEntityData.clear();
}
/**
* Checks if entity exists inside of array
* #param uuid
* #return
*/
public boolean doesEntityExist(StringArrayHolder entityData)
{
List<int[]> entityLoc = allEntityData.get(entityData);
if(entityData != null)
{
return true;
}
return false;
}
}
and the wrapper:
package timeTraveler.core;
import java.util.ArrayList;
public class StringArrayHolder
{
private String[] data;
public StringArrayHolder()
{
data = new String[2];
}
public void setData(String[] data)
{
this.data = data;
}
public String[] getData()
{
return this.data;
}
#Override
public int hashCode()
{
return 0;
//...
}
#Override
public boolean equals(Object o)
{
if(data.equals(o))
{
return true;
}
return false;
//...
}
}
The problem is that arrays don't override equals nor hashCode methods from Object class, thus even if you add a new String[] with the same values, it will be a different key in your map.
A possible solution would be creating a wrapper class that will hold the String[] for you and override the equals and hashCode methods there.
public class MyStringArrayHolder {
private String[] data;
//class constructor...
//getters and setters for the array...
#Override
public int hashCode() {
//...
}
#Override
public boolean equals(Object o) {
//...
}
}
For the implementations of equals and hashCode methods, you can use Arrays#equals and Arrays#hashCode in this wrapper class.
From your comment:
My addEntity method is the problem. I am trying to detect of the key is already in the hashmap, and if it is, then do nothing. However, it for some reason will always add the key, no matter if the key already exists.
This is what I've explained above. The method Map#containsKey clearly states this:
returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k))
Since arrays does not override Object#equals, you won't have two similar array keys even if they have the same elements in the same position.
EDIT: based on your current edit, the problems are in the equals and hashCode methods implementation. I've made a basic implementation of the MyStringArrayHolder class and copied/pasted the code of the PathingData class. This works as expected (at least for this case):
class MyStringArrayHolder {
private final String[] data;
//I do not want any client could change the array reference
//this also explains why this field doesn't have a setter
public MyStringArrayHolder(String[] data) {
this.data = data;
}
public String[] getData() {
return this.data;
}
#Override
public int hashCode() {
return Arrays.hashCode(data);
}
#Override
public boolean equals(Object o) {
if (o == null) return false;
if (o == this) return true;
if (o instanceof MyStringArrayHolder) {
MyStringArrayHolder other = (MyStringArrayHolder)o;
return Arrays.equals(this.data, other.data);
}
return false;
}
//just to print in console for testing purposes
#Override
public String toString() {
return Arrays.deepToString(data);
}
}
public class PathingData {
//removed the static modifier, not really sure why you need it like that
public Map<MyStringArrayHolder, List<int[]>> allEntityData;
//current class implementation...
//just to print in console for testing purposes
#Override
public String toString() {
return allEntityData.toString();
}
public static void main(String[] args) {
PathingData pathingData = new PathingData();
String[] example1 = { "hello", "world" };
String[] example2 = { "luiggi", "mendoza" };
String[] example3 = { "hello", "world" };
MyStringArrayHolder holder1 = new MyStringArrayHolder(example1);
MyStringArrayHolder holder2 = new MyStringArrayHolder(example2);
MyStringArrayHolder holder3 = new MyStringArrayHolder(example3);
pathingData.addEntity(holder1);
pathingData.addEntity(holder2);
pathingData.addEntity(holder3);
pathingData.addData(holder1, "1,2,3");
pathingData.addData(holder2, "4,5,6");
pathingData.addData(holder3, "7,8,9");
System.out.println(pathingData);
}
}
Output:
Adding entity!
Adding entity!
ENTITY ALREADY EXISTS IN ARRAY
Adding data to entity!
Adding data to entity!
Adding data to entity!
{[luiggi, mendoza]=[[I#35087359], [hello, world]=[[I#5a7691c0, [I#1e5b02a6]}
Note: the last line containing [I#35087359 is the current hash code of the int[]. I would recommend to change from List<int[]> to List<List<Integer>>, but this implementation is outside the scope of the question :).
I have a StockList class which contains a linkedlist and can control stock using a variety of method. However i am stuck on what to put inside my method body for my updateItemPrice method.
Do I need to use a setter to set the new item price, if so how would i go about that?
This is my code so far, any help would be much appreciated!
import java.util.*;
public class StockList {
{
private LinkedList<StockItem> stock
= new LinkedList<StockItem>();
public StockList() {};
// Adds item to end of stock list
public void addItem(StockItem item)
{
this.stock.addLast(item);
}
// Removes item identified by productID from stock list
public void deleteItem(String itemID)
{
ListIterator itr = stock.listIterator();
while(itr.hasNext())
{
StockItem item = (StockItem)itr.next();
if(item.getitemID() == itemID)
{
stock.remove(itr.previousIndex());
break;
}
}
}
// Updates price of existing item
public void updateItemPrice(String itemID, double price)
{
???
}
// Updates quantity of existing item
public void updateItemQuantity(String itemID, int quantity)
{…}
// Updates re-order level of existing item
public void updateReOrderLevel(String itemID,
int reOrderLevel)
{…}
// Returns formatted representation of the stock list
public String formatStockList()
{…}
// Returns formatted representation of re-order list
// Items are on this list if quantity < reOrderLevel
public String formatReOrderList()
{…}
}
}
StockItem need to have the setter method to set Price like setPrice
ListIterator itr = stock.listIterator();
while(itr.hasNext())
{
StockItem item = (StockItem)itr.next();
if(item.getitemID() == itemID)
{
item.setPrice(price);
break;
}
}
How ever there is also problem in your delete code...
public void deleteItem(String itemID)
{
ListIterator itr = stock.listIterator();
while(itr.hasNext())
{
StockItem item = (StockItem)itr.next();
if(item.getitemID() == itemID)
{
stock.remove(itr.previousIndex());
break;
}
}
}
This will give you concerrent Access exception. use below code instead.
public void deleteItem(String itemID)
{
ListIterator itr = stock.listIterator();
while(itr.hasNext())
{
StockItem item = (StockItem)itr.next();
if(item.getitemID() == itemID)
{
itr.remove(); // Removes last obejct returned by itr.next()
break;
}
}
}
ListIterator itr = stock.listIterator();
while(itr.hasNext())
{
StockItem item = (StockItem)itr.next();
if(item.getitemID() == itemID)
{
item.setPrice(price);
break;
}
}
Nevertheless, it may be a better idea to use an HashMap<String, StockItem>() to store the ids of the stock objects and update the price would be more easy for you.
And you should store ids as Long instead of String, so this would be an HashMap<Long, StockItem>()
Since you have an itemId, I would not use a List. I would use a Map, with itemId as the key and the StockItem as the value. Then your add and delete methods become much simpler
Map<String, StockItem> stocks = new HashMap<String, StockItem>();
public void addStockItem(StockItem stockItem) {
this.stocks.put(stockItem.getItemId(), stockItem);
}
public void deleteStockItem(StockItem stockItem) {
this.stocks.remove(stockItem.getItemId());
}
then updating becomes as simple as getting the appropriate item out of the map and updating its price.
public void updateStockItem(String id, Double price) {
StockItem item = this.stocks.get(id);
item.setPrice(price);
}
// Updates price of existing item
public void updateItemPrice(String itemID, double price)
{
ListIterator itr = stock.listIterator();
while(itr.hasNext())
{
StockItem item = (StockItem)itr.next();
if(item.getitemID() == itemID)
{
item.setPrice(price);
break;
}
}
}
Everybody's answer here except #hvgotcodes has a very basic bug:
if(item.getitemID() == itemID) // this won't work!
#hvgotcodes solution is the correct way of implementing your class. Using a HashMap is far better than iterating over LinkedList to delete stuff.