Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Pointers?

 
Ben Roy
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A little confusion here on my part:
Following up on a question I had below, I have an ArrayList of cartItem objects. Each cartItem has a qty property, which may need to be updated.
cart.updateQty(cartItem myItem, int qty)
{
}
What I'm trying to figure out is how I can update the qty if the cartItem already exists in the ArrayList. For example, in C++ I'd just reference that particular cartItem in the ArrayList and set the qty value. But I don't think java has references. So if I do this:
//First line returns a cartItem
itemToUpdate = cartList.get(whateverTheIndexIs);
itemToUpdate.qty = newQty;
itemToUpdate is a copy of the item in the array, right? So now to have the updated on in the arrayList I need to remove the one in the array list and insert itemToUpdate? Is that how it works?
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

What I'm trying to figure out is how I can update the qty if the cartItem already exists in the ArrayList. For example, in C++ I'd just reference that particular cartItem in the ArrayList and set the qty value. But I don't think java has references. So if I do this:
//First line returns a cartItem
itemToUpdate = cartList.get(whateverTheIndexIs);
itemToUpdate.qty = newQty;
itemToUpdate is a copy of the item in the array, right? So now to have the updated on in the arrayList I need to remove the one in the array list and insert itemToUpdate? Is that how it works?[/B]

First of all, almost everything in Java is a reference. Only primitive data types aren't stored as references. If you have an item object variable, it really contains a reference to that object, not the object itself, as in C++. The code snippet you've supplied will update the qty of the item within the list because, by executing the first line, you're really just obtaining a reference to the object in the list, not a copy of that object. There's no need to replace the one in the list because that's the one that you're modifying.
Corey
[This message has been edited by Corey McGlone (edited December 20, 2001).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic