Avatar of bachra04
bachra04
Flag for Canada asked on

store a reference to object into string

I have the following problem:
I created an object A and want to store a reference of object A in a string so that I can retrieve it later (similar way as in C++ when we can keep a pointer to an object in uint32). Is there a way to do that in java ?

Thanks
Java

Avatar of undefined
Last Comment
bachra04

8/22/2022 - Mon
CEHJ

No - that's not possible. A reference in Java could be stored in a Map, with an appropriate key though
ksivananth

you don't have to store it in a string, you'll store the reference in its type, for e.g., if A is your class,

A a  = new A() ; //here 'a' holds the reference of instance A and u can use 'a' as the reference later
bachra04

ASKER
Ok if I store my object in a map, is it possible later to retrieve it by storing the key into string ?
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
bachra04

ASKER
to Ksivananth :

No I need to store it in reference because I’m using a third party API that allows me to use String only to pass the object handle (reference)
ksivananth

whats  your object type? if its String,

String str = "Your String" ;
ksivananth

and then pass str to the API!
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
for_yan

If that third party API is not in Java you probably need to go through JNI (Java Native Interface).
If it is in Java, you usually don't need to worry about the handles, so it is probably after all not in Java
bachra04

ASKER
My object is not of type String
CEHJ

>>I’m using a third party API that allows me to use String only to pass the object handle (reference)

What kind of string - a Java string?
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
bachra04

ASKER
yes a java string
ksivananth

>>My object is not of type String

either it should have String conversion built in( toString override? ) or you need to build one!
bachra04

ASKER
Yes OK,
Let’s say I override my object toString method().
Then how can I retrieve back my object using only the String  ? is it unique?
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
ksivananth

>>Then how can I retrieve back my object using only the String  ?

why do you want to retrieve back from String while you have the object reference already!
for_yan

No you cannot go back from toString() to your object.

What you can do is to generate some unique string - say orresponding to the timestamp
and store your object in the HashMap with that string as a key.
Then if you are dealing with java software you can pass to that software this hashmap and this string as a key
and the information on the object type and then
your object can be retrieved within that software.
bachra04

ASKER
Thank you yan,
Does the timestamp guarantee me No collision in the hashMap ?
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
for_yan

You can probably also use the hashcode() method of the Object calss to generate
unique string for the object.
However, this string alone will not be enough to retrieve the object back, unless
you store the object itself  in some Map container and give your software access to that container
CEHJ

Java allows no direct pointer access so you can't get a pointer to cast.  It's however conceivable that you could serialize the whole object into a string and then deserialize it, but of course the 'other end' need to know how to do that.
for_yan

Well, I think hashcode is better solution, though I never tried it myself - I always had some natural
strings to store as a key
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Mick Barry

you need to generate a hashcode of the object, using something like SHA1 (or MD5)
that will give you a unique value
bachra04

ASKER
to CEJH :

Yep I have this possibility.
Does that guarantee uniqueness of the string ?
Is there any sample code how to serialize/deserialize to a string ?

Thanks
for_yan

Timestamp does not guarantee uniqueness, but when storing the next object you can check the hashmap
and if such key already exists you can pick up next timestamp up to the point when theere is no
such key in the Map - that may slow down a bit your operation if
you plan to get them stored very quickly.
So hashcode should work.
Your help has saved me hundreds of hours of internet surfing.
fblack61
ksivananth

>>Well, I think hashcode is better solution

I don't think it helps... how does the 3rd party app know the valye can be retrieved from a map and how does it get the referenec of the map...

you should read their API doc and see what they expect the String to contain... you can not simply assume and send something on your own!
for_yan

If you can pass a Map to your third party API, you rather don't want to serialize - that would be
some time consuming ioperation, I guess
Mick Barry

No a timestamp is not going to help you. Certainly won't be unique.
If you just want to generate a random id then you can use UUID
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
for_yan

thisd is about hashcode() method:

hashCode

public int hashCode()

    Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.

    The general contract of hashCode is:

        * Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
        * If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
        * It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.

    As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

    Returns:
        a hash code value for this object.
    See Also:
        equals(java.lang.Object), Hashtable

bachra04

ASKER
So to sum up  : two possible solutions :

1st solution :  using hashMap but ensure the key is unique

2nd solution : serialize /deserialize the into a string ( some extra overhead)
Mick Barry

> 2nd solution : serialize /deserialize the into a string ( some extra overhead)

thats not really practical, and offers you no advantages.
and will be very hard to make it unique
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
ksivananth

>>using hashMap but ensure the key is unique

does the API allows map?

>>serialize /deserialize the into a string ( some extra overhead)

does the API know the data has to be deserialized?
bachra04

ASKER
to Ksivananth :

My code  calls the API in the client side and pass the string.

My code on the server side uses the API and get the string

Mick Barry

a decent hash (eg.SHA1) or UUID should do the job then
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
ksivananth

r u  just using the API to pass value from client and get values in Server? doesn't the API do something on the value passed in?
ksivananth

As I said you should read the API doc well and understand their expectation...
CEHJ

As k. said, we need to know something about the api. A hashcode or uuid is irrelevant: what you seem to be wanting is a pointer (which you can't have) but knowing something about how the api works might help.

If it REALLY needs a pointer as a String then you'd probably need to have created a vm in native code. That way, you can manipulate pointers
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
bachra04

ASKER
The API is in Java and accepts Java Strings only.
for_yan

That sounds kind of confusing.
If you are passing this object from one computer to another
(e.g. from client to server or vice versa) then in general situation you of course cannot rely on any
HashMap conatainers because you'll need to pass your whole HashMap when you
want just one object;  then you should rather pass object itself in serialized form.
It is only in case when both client and server happen to have access to the same HashMap, that
you can just pass only the key between each other.
In this special case the HashMap with hashcodes of the objects as keys should probably work, but you should
be careful that both client and server should have access to the same HashMap.

bachra04

ASKER
To  for yan:

They are not running on different machine neither on on different processes, they both have access to the HashMAp (It is kind of Software Design Tool).
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
CEHJ

>>The API is in Java and accepts Java Strings only.

It would help if you could show documentation for the method you're calling.
CEHJ

>>they both have access to the HashMAp

So there IS a HashMap? If it's shared, then they might want you to pass the key as i mentioned earlier, but all this guesswork is kind of pointless
SOLUTION
for_yan

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
bachra04

ASKER
Do SHA1 or UUID guarantee uniqueness ?
I was thinking about something simpler :  have a static Counter Object;
Whenever I add a new object into the Map , I get the Id from the Counter (which will be automatically incremented)

Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
ASKER CERTIFIED SOLUTION
Mick Barry

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
CEHJ

Yes you can use a counter. That WOULD guarantee uniqueness
Mick Barry

SOLUTION
CEHJ

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
bachra04

ASKER
Thank you guys, you all contributed very well to solve this issue
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
CEHJ

You don't need to reinvent Java maps with UUID/SHA btw: all that will happen there if you do is that you'll slow everything down
ksivananth

>>you all contributed very well to solve this issue

honestly I don't understand how it solves your problem... :(
bachra04

ASKER
without unique keys, there is usually possibility of key collision
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
bachra04

ASKER
>> honestly I don't understand how it solves your problem... :(

I need to pass and retrieve my object using String  (using HashMap and unique key that has solved my problem )