• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Liutauras Vilda
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • fred rosenberger
  • salvin francis
Bartenders:
  • Piet Souris
  • Frits Walraven
  • Carey Brown

referring to a specific object

 
Ranch Hand
Posts: 61
1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose I create a class representing the usual 52 playing cards. When I create the 52 objects from this class,
how can I refer to a specific card? Must I put each card into an array and search for the card I want?

 
Marshal
Posts: 25682
69
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, you'll want to put them into some kind of a collection. If you're just beginning Java then you may not have learned about collections yet, so then searching through an array would be something you know how to do.

But you could use a Map<String, Card> and then use a String like "3D" to search the Map and directly find the Card which represents the 3 of Diamonds, for example. That might be generally a useful solution for whatever it is you plan to do with the cards, although we (and maybe you too) don't know what that is.

It may be that searching for a Card given its name isn't particularly useful after all. For example maybe you want to deal out Cards into poker hands, in which case you could deal a Hand with references to the right number of Cards. No searching required to do that.
 
Marshal
Posts: 69831
278
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You mean a class representing a card which you make fifty‑two objects from? Remember you cannot so much find an object as find a reference pointing to that object; the difference is subtle but significant. Searching an array will tell you whereabouts in that array you have the reference.

There are several ways you can find instances. But before you do anything with cards, read the JLS (=Java® Language Specification). You may need to scroll down several pages. Note the example there uses the same suit order as you would for Contract Bridge.
I suggest you can put the Card objects into a Map as a “K”. Make sure to make Card immutable and give it correct hashCode() and equals() methods. If you make that a Map<Cad, Integer>, you can use the “V” to record its index in a List or similar.
 
Sheriff
Posts: 15795
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A bit of a tangent but if you're going to create a Card class, you might want to study up on Enumerated types if you haven't already: https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
 
Dan Bromberg
Ranch Hand
Posts: 61
1
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Once again, thanks to all those who have replied.

My real question is not so much about the Card class as it is for what's really going on when many objects from a class are created?
I am trying to visualize all these objects in memory and am basically looking for the best way to picture how they communicate with one another.
For example, if I wanted all those objects that have an identical attribute, eg, first name, or which has the largest attribute numeric value, etc...
then how does this communication amongst them occur?

If I can't picture how this is happening then it makes my coding cloudy for design and analysis.

Dan
 
Campbell Ritchie
Marshal
Posts: 69831
278
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want them all to have an identical attribute, that can be done by giving them a field that always has the same value, like a constant.
As to how thy inter&#c2011;communicate, you would have to decide that and write code for it.
If you want to find the “largest”, go through that JLS section I linked to yesterday.
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Dan Bromberg wrote:

My real question is not so much about the Card class as it is for what's really going on when many objects from a class are created?

Dan



It's hard to fully answer your questions here without copying a few paragraphs worth of information, I'll try to help as best I can. Basically, what's happening is that when you create an object from your class, Java takes a copy of the class and makes a nice little spot for it on the heap (where object types are stored in memory).
One problem I would predict you have had or will have is referencing each object. You need to individually create each Card object using the same class, but with different names (an easy way of doing this is to use a for loop**). Each name is a reference that goes on the stack (a reference is simply a name that refers to the object that is on the heap, like an address).

Like Ritchie said, constants are definitely something you will need for this. This is because when you create the object, each object has it's own variables (remember, each object is a COPY of the original class), the nice part about constants is they are the same as a instance or local variable for your class, except they stay constant for all of the objects of the Cards class.  So if you wanted to count how many Card objects you've made, you would add an if statement that adds 1 to a constant variable every time the a Card object is made. You wouldn't be able to do that with any other variable because it would just be a copy of the original Card object so the count would restart.

I hope that helped. If it didn't, I hope you at least learned something.

**There are a ton of other (probably better) ways of referencing them, one might be to use the built-in ArrayList class that has methods to easily take care of your Card objects.
 
Dan Bromberg
Ranch Hand
Posts: 61
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:If you want them all to have an identical attribute, that can be done by giving them a field that always has the same value, like a constant.
As to how thy inter&#c2011;communicate, you would have to decide that and write code for it.
If you want to find the “largest”, go through that JLS section I linked to yesterday.



Sorry, I wasn't clear. By identical attribute I meant any of the attributes that each object of the class will have upon its creation.
Dan
 
Paul Clapham
Marshal
Posts: 25682
69
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Dan Bromberg wrote:I am trying to visualize all these objects in memory and am basically looking for the best way to picture how they communicate with one another.
For example, if I wanted all those objects that have an identical attribute, eg, first name, or which has the largest attribute numeric value, etc...
then how does this communication amongst them occur?



You can't communicate with Object X unless you have a reference to it. And then you communicate with it by calling its methods, at least those methods which are accessible to you.

So your next question, naturally, is "Then how do I get a reference to Object X?" And the answer to that is, something else which has a reference to Object X passes you a copy of that reference. And how does that something else do that? Mostly it calls one of your methods which is written to accept a reference to something of Object X's type, and you then use that reference. You could save it for later use too.

That's all very hand-wavy, though. So let's make up an example with Card objects. First of all something might generate a collection of 52 Card objects (unless you're playing euchre or something) and store them in a collection -- a Set, a List, an array, etc. So it has a reference to each of the 52, or more precisely it can get a reference from the collection.

That something might have a "deal" method which produces a Hand object, or several of them. A Hand object would have a fixed number of Card objects, or more precisely references to them. It might have other information too, like whether each of the Cards was visible to other players. So now if you have a reference to a Hand object you can get references to its Card objects by calling one of its methods. You might be a Player object, for example, which is given a Hand object via its constructor.

And you might have a Game object, which knows the rules of the game you're playing. Perhaps you could call a Game method which takes two Card objects, and it tells you in return which of the Cards beats the other one.

I've seen lots of beginner posts in this forum and they all seem to be asking about code which does nothing at all to prepare the beginner for this sort of design, which is really what the vast majority of real-life Java programming does. So I don't think you are alone.
 
Junilu Lacar
Sheriff
Posts: 15795
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Dan Bromberg wrote:
I am trying to visualize all these objects in memory and am basically looking for the best way to picture how they communicate with one another.
For example, if I wanted all those objects that have an identical attribute, eg, first name, or which has the largest attribute numeric value, etc...


Please be careful about how you word things. Campbell has interpreted "objects that have an identical attribute, eg, first name..." as something like a bunch of objects with the firstName attribute of "Bob" or some such. I don't find that particularly useful and I don't think that's what you meant, is it? Also, you started out talking about playing cards and then suddenly segued to objects with a first name attribute. That kind of muddles the conversation because why would a Card have a first name? And then it seems you switch context again with "largest attribute numeric value." If you want to get clarity, don't start out with a confusing question that's open to different interpretations or has a mix of contexts. Stick to one context and give concrete examples.

how does this communication amongst them occur?


Objects communicate with each other via "messages" or "calls". In order for one object to communicate with another, the "sender" needs a reference to the "recipient." It's kind of like a telephone system in the real world. If you and your friend want to communicate via phone, then the caller will need to know the callee's phone number. Likewise, an object needs a reference to any other object with which it wants to communicate. Once an object has a reference to another object, it can call or invoke any methods that the other object makes available to other objects. Take for example this class:

In order to interact with an object of type Phone, you might have this kind of code:

This class defines a RoboCaller object as an object that has a method named spam() which takes a list of Phone objects. By iterating through this list, the target variable declared on line 4 becomes a reference to one Phone object in the numbers list. Line 5 invokes the call() method of that particular Phone object. Later on, on line 7, the RoboCaller object will call the leaveVoiceMail() method of the same Phone object. Each time the body of the for-loop is executed, it will be with a different Phone object until all Phone objects in the numbers list have been "called".

You'll also notice that the Phone class defines several public methods and one private method, reviewVoiceMail(). Because the method is private, a RoboCaller object will not be able to call it.

This is just an example of a few things you can do with objects. The possibilities are endless and limited only by your imagination and what you actually need to do to solve a specific problem. I'll stop here and let you digest that a little.
 
Campbell Ritchie
Marshal
Posts: 69831
278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, I appear to have misunderstood the bit about identical fields.

Each class defines which fields its objects have. If you want a PrisonerOfWar class you would give it the following three fields: name, rank, and number. Each PriosonerOfWar object will have a value for name, rank, and number, unless some mistake has been made. In the case of a Card class (not Cad; my spelling wasn't very good), it might have fields called suit and face. I presume you looked at those examples in the JLS.

Joshua Vanrenterghem wrote:. . . each object is a COPY of the original class

No, objects aren't copies of classes. They are made from the instructions given in the class.

the nice part about constants is they are the same as a instance or local variable for your class, except they stay constant for all of the objects of the Cards class. . . .

Afraid that doesn't sound like a description of constants; It sounds more like static fields. People are sometimes shown a static variable for counting instances, but that isn't a reliable technique. It often cannot tell when an object goes out of use. It probably isn't right to liken fields to local variables; local variables only exist inside the method they are declared in. Maybe you meant instance variables rather than local variables.
 
Campbell Ritchie
Marshal
Posts: 69831
278
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Dan Bromberg wrote:. . . what's really going on when many objects from a class are created? . . .

Imagine a production line with cars coming off it. But they don't have to be all black; they can be given different colours and different sizes of engine.
Now imagine that rather than making all that out of steel rubber and plastic, you are making it out of tiny electric charges occupying an area much smaller than 1μm each way on a silicon chip.
 
Junilu Lacar
Sheriff
Posts: 15795
264
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Joshua Vanrenterghem wrote:Basically, what's happening is that when you create an object from your class, Java takes a copy of the class and makes a nice little spot for it on the heap (where object types are stored in memory).
One problem I would predict you have had or will have is referencing each object. You need to individually create each Card object using the same class, but with different names (an easy way of doing this is to use a for loop**). Each name is a reference that goes on the stack (a reference is simply a name that refers to the object that is on the heap, like an address).

Like Ritchie said, constants are definitely something you will need for this. This is because when you create the object, each object has it's own variables (remember, each object is a COPY of the original class), the nice part about constants is they are the same as a instance or local variable for your class, except they stay constant for all of the objects of the Cards class.  So if you wanted to count how many Card objects you've made, you would add an if statement that adds 1 to a constant variable every time the a Card object is made. You wouldn't be able to do that with any other variable because it would just be a copy of the original Card object so the count would restart.


There are quite a number of inaccurate statements that make all this almost but not quite right.

As already pointed out, instantiating a class does not create a copy of the class. It's correct to say that "a nice little spot for it on the heap" gets carved out but what that spot consists of essentially is memory space for instance variables defined by the class and some overhead for directing method calls to each object. Search for what do java objects look like in memory or take a look at this article to get a better idea: https://www.programcreek.com/2011/11/what-do-java-objects-look-like-in-memory/

The statement that you need "different names" for each object created is also not quite right. It's true that it's one way to use/reuse an object reference but it's not the only way. You can use an object reference on the fly, for one-off kind of tasks. In this case, you won't need to assign the object reference to a variable for later reuse. Also, if you store the references in a collection or array you won't need different names. You access those objects through the collection. Again, you don't even have to name this collection/array to do that. Take a look at this code, for example:

The "Look, ma, no name!".toCharArray() expression resolves to an unnamed char[] which the enhanced for-loop will then iterate over by assigning each successive element to the ch loop variable.

The second paragraph just makes a veritable word salad of "variable", "constant", "copy", "class", and "object" -- sorry, but I can't even start sorting it out. I think maybe Campbell has a better sense of what you're actually trying to explain though.
 
Dan Bromberg
Ranch Hand
Posts: 61
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Paul Clapham wrote:

Dan Bromberg wrote:I am trying to visualize all these objects in memory and am basically looking for the best way to picture how they communicate with one another.
For example, if I wanted all those objects that have an identical attribute, eg, first name, or which has the largest attribute numeric value, etc...
then how does this communication amongst them occur?



You can't communicate with Object X unless you have a reference to it. And then you communicate with it by calling its methods, at least those methods which are accessible to you.

So your next question, naturally, is "Then how do I get a reference to Object X?" And the answer to that is, something else which has a reference to Object X passes you a copy of that reference. And how does that something else do that? Mostly it calls one of your methods which is written to accept a reference to something of Object X's type, and you then use that reference. You could save it for later use too.

That's all very hand-wavy, though. So let's make up an example with Card objects. First of all something might generate a collection of 52 Card objects (unless you're playing euchre or something) and store them in a collection -- a Set, a List, an array, etc. So it has a reference to each of the 52, or more precisely it can get a reference from the collection.

That something might have a "deal" method which produces a Hand object, or several of them. A Hand object would have a fixed number of Card objects, or more precisely references to them. It might have other information too, like whether each of the Cards was visible to other players. So now if you have a reference to a Hand object you can get references to its Card objects by calling one of its methods. You might be a Player object, for example, which is given a Hand object via its constructor.

And you might have a Game object, which knows the rules of the game you're playing. Perhaps you could call a Game method which takes two Card objects, and it tells you in return which of the Cards beats the other one.

I've seen lots of beginner posts in this forum and they all seem to be asking about code which does nothing at all to prepare the beginner for this sort of design, which is really what the vast majority of real-life Java programming does. So I don't think you are alone.



Paul,
I am not surprised that storing the objects in a collection for later reference seems to be the way to go.
I was just wondering if there was a more direct technique that Java offered which I was unaware of but apparently not.
Thanks for your thoughts!
Dan
 
Dan Bromberg
Ranch Hand
Posts: 61
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moderator edit: deleted long quote -- @OP: Please avoid quoting entire posts, especially if they're long. Quote only the relevant parts that can help give context to your reply. Thanks.

Junilu,
Thanks very much for your detailed explanation and example. Also, apologies for my vagueness and wording. As you pointed out, I realize now that switching my example was not a smart way to describe my issue. I should have not provided anything specific and stated my question as a general request for how to envision referencing multiple objects in memory. I like your telephone analogy and it did help clarify my question, so thank you for that! Iterating through a list of references makes good sense; I was just curious if Java offered any more clever alternatives.
All the best,
Dan
 
Saloon Keeper
Posts: 2622
128
Google Web Toolkit Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Dan Bromberg wrote:... Iterating through a list of references makes good sense; I was just curious if Java offered any more clever alternatives. ...


Yes, there is a more clever alternative to search something like this within java. Hint: It was discussed in this post 3 days ago.
 
Dan Bromberg
Ranch Hand
Posts: 61
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:

Dan Bromberg wrote:. . . what's really going on when many objects from a class are created? . . .

Imagine a production line with cars coming off it. But they don't have to be all black; they can be given different colours and different sizes of engine.
Now imagine that rather than making all that out of steel rubber and plastic, you are making it out of tiny electric charges occupying an area much smaller than 1μm each way on a silicon chip.



Not quite the animated image I had of how objects communicate with one another but thanks for your suggestion.
Dan
 
Dan Bromberg
Ranch Hand
Posts: 61
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:You mean a class representing a card which you make fifty‑two objects from? Remember you cannot so much find an object as find a reference pointing to that object; the difference is subtle but significant. Searching an array will tell you whereabouts in that array you have the reference.

There are several ways you can find instances. But before you do anything with cards, read the JLS (=Java® Language Specification). You may need to scroll down several pages. Note the example there uses the same suit order as you would for Contract Bridge.
I suggest you can put the Card objects into a Map as a “K”. Make sure to make Card immutable and give it correct hashCode() and equals() methods. If you make that a Map<Cad, Integer>, you can use the “V” to record its index in a List or similar.



Thanks, Campbell - storing the references in an array seems to be the basic approach if you're not sure if you'll ever need to go back to massage that object during program execution.
Dan
 
Dan Bromberg
Ranch Hand
Posts: 61
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Junilu Lacar wrote:

Joshua Vanrenterghem wrote:Basically, what's happening is that when you create an object from your class, Java takes a copy of the class and makes a nice little spot for it on the heap (where object types are stored in memory).
One problem I would predict you have had or will have is referencing each object. You need to individually create each Card object using the same class, but with different names (an easy way of doing this is to use a for loop**). Each name is a reference that goes on the stack (a reference is simply a name that refers to the object that is on the heap, like an address).

Like Ritchie said, constants are definitely something you will need for this. This is because when you create the object, each object has it's own variables (remember, each object is a COPY of the original class), the nice part about constants is they are the same as a instance or local variable for your class, except they stay constant for all of the objects of the Cards class.  So if you wanted to count how many Card objects you've made, you would add an if statement that adds 1 to a constant variable every time the a Card object is made. You wouldn't be able to do that with any other variable because it would just be a copy of the original Card object so the count would restart.


There are quite a number of inaccurate statements that make all this almost but not quite right.

As already pointed out, instantiating a class does not create a copy of the class. It's correct to say that "a nice little spot for it on the heap" gets carved out but what that spot consists of essentially is memory space for instance variables defined by the class and some overhead for directing method calls to each object. Search for what do java objects look like in memory or take a look at this article to get a better idea: https://www.programcreek.com/2011/11/what-do-java-objects-look-like-in-memory/

The statement that you need "different names" for each object created is also not quite right. It's true that it's one way to use/reuse an object reference but it's not the only way. You can use an object reference on the fly, for one-off kind of tasks. In this case, you won't need to assign the object reference to a variable for later reuse. Also, if you store the references in a collection or array you won't need different names. You access those objects through the collection. Again, you don't even have to name this collection/array to do that. Take a look at this code, for example:

The "Look, ma, no name!".toCharArray() expression resolves to an unnamed char[] which the enhanced for-loop will then iterate over by assigning each successive element to the ch loop variable.

The second paragraph just makes a veritable word salad of "variable", "constant", "copy", "class", and "object" -- sorry, but I can't even start sorting it out. I think maybe Campbell has a better sense of what you're actually trying to explain though.



Junilu,
Thanks for your search results links; I found them helpful and should've Googled them myself rather than bothering the community with my vague muse.
Dan
 
"How many licks ..." - I think all of this dog's research starts with these words. Tasty tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    Bookmark Topic Watch Topic
  • New Topic