Reputation: 3
I am new in java and i dont know how can I solve the problem. My problem is that I have a list with sacks and every stack have persons inside and the persons a string(Name). so list -> stack-> person with name
My question is how can I get the name?
((Stack)list.getObject()
getObject gives me the current object in the list(this works) but I have no idea for the name :((Stack)list.getObject().(Person)stack.top().Name
was one idea but it's wrong
Upvotes: 0
Views: 148
Reputation: 11
You just need more brackets but it's easier to put as different line.
((Person)((Stack)list.getObject()).stack).top().Name
Upvotes: 0
Reputation: 1936
Another option is:
((Person)((Stack)list.getObject()).top()).Name
However, this isn't all that readable, so let's break it down by the steps that we take to get this:
Get the object:
list.getObject()
Cast this to a Stack
object:
(Stack)list.getObject()
Call top()
on the stack (note parentheses around the last so we know what we're calling it on):
((Stack)list.getObject()).top()
Cast this to a Person
object:
(Person)((Stack)list.getObject()).top()
Retrieve the Name
field (noting more parentheses again):
((Person)((Stack)list.getObject()).top()).Name
Now, as for readability, I would much more recommend wassgren's answer, but if for some reason you absolutely must have this take up on line, that's how you do it.
Upvotes: 0
Reputation: 19231
You had the right idea but the wrong syntax. Try this way:
Stack stack = (Stack) list.getObject();
Person person = (Person) stack.top();
String name = person.Name;
Upvotes: 4