jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes Pointers? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Pointers?" Watch "Pointers?" New topic
Author

Pointers?

Ben Roy
Ranch Hand

Joined: Nov 01, 2000
Posts: 70
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

Joined: Dec 20, 2001
Posts: 3271

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).]


SCJP Tipline, etc.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Pointers?
 
Similar Threads
inconsistent ajax calls to servlet functions
pass the values from HTML to jsp page
Passing values to form bean string array
PreparedStatement (passing in an Array)
urgent getting parameters