Click here to Skip to main content
14,333,647 members
Rate this:
Please Sign up or sign in to vote.
See more:
I have class:
public class HarddriveStorage {
...
}


I make instances of the created class:
HarddriveStorage hds1 = new HarddriveStorage ();
HarddriveStorage hds2 = new HarddriveStorage ();
HarddriveStorage hds3 = new HarddriveStorage ();


Then I add them to a linked list:
LinkedList hdList = new LinkedList();
hdList.add(hds1);
hdList.add(hds2);
hdList.add(hds3);


When I want to access the objects, I get a reference instead of value:
hdList.get(1);


I get:
org.cloudbus.cloudsim.HarddriveStorage@578486a3


What should I do to get "hds2" for example in return?

What I have tried:

I have read documents on the web, but couldn't make it.
Posted
Updated 6-Jun-19 2:46am
v2
Rate this:
Please Sign up or sign in to vote.

Solution 1

Your method is fine. org.cloudbus.cloudsim.HarddriveStorage@578486a3 is just the string representation of the object.

Edit:

Because .get returns an Object, you have to cast the return value back to HarddriveStorage:
HarddriveStorage myHD = (HarddriveStorage)hdList.get(1);
   
v3
Comments
Ali Majed HA 5-Jun-19 8:43am
   
I want to access methods and variable of the object. How should I do it?
Thomas Daniels 5-Jun-19 8:44am
   
HarddriveStorage yourObject = hdList.get(1);
yourObject.callYourMethod();
Ali Majed HA 5-Jun-19 8:49am
   
If I say:
HarddriveStorage MyHD = hdList.get(1);

The error is:
"incompatible types: Object can not be converted to HarddriveStorage."

and if I say:
Object MyHD = hdList.get(1);

I can't access the methods inside HarddriveStorage.
MyHD.
just give me a limited choices.
Thomas Daniels 5-Jun-19 8:51am
   
Oh right, LinkedList stores objects. You have to cast the return value to HarddriveStorage like this:

HarddriveStorage myHD = (HarddriveStorage)hdList.get(1);
Ali Majed HA 5-Jun-19 9:00am
   
Thanks a lot my friend.
CPallini 5-Jun-19 8:57am
   
Suppose your HarddriveStorage has a method called brand() then you may write
HarddriveStorage h1 = (HarddriveStorage)hdlist.get(1);
String h1brand = h1.brand();

Note the cast is required because you are using a non generic container.
Ali Majed HA 5-Jun-19 8:58am
   
That's it! Thanks a lot.
CPallini 5-Jun-19 11:55am
   
You are welcome.
Rate this:
Please Sign up or sign in to vote.

Solution 2

Quote:
When I want to access the objects, I get a reference instead of value:

Quote:
What should I do to get "hds2" for example in return?

hds2 is just the name of the variable, it is not the value of the object.
get returns a reference to the object and you may use it to retrieve all the properties of such object.
   
Comments
Ali Majed HA 5-Jun-19 8:41am
   
How can I access to the methods and variables of "hds2" object?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100