Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Confused with vectors and datatypes

Status
Not open for further replies.

JontyMC

Programmer
Nov 26, 2001
1,276
GB
I am very confused why the following code doesn't work. The observer object creates an observer with userName = jon.

Code:
Observer observer = new Observer("jon");
Vector observersList = new Vector();
observersList.add(observer);
System.out.println(observer.userName);
System.out.println(observer.getClass());
System.out.println(observersList.elementAt(0).getClass());
System.out.println(observer.equals(observersList.elementAt(0)));

The output for each line is:

Code:
jon
Observer
Observer
true

but when I insert the following line:

Code:
System.out.println(observersList.elementAt(0).userName);

I get an compilation error saying cannot resolve symbol userName. Whats going on here? I am v confused.

Jon
 
observersList is of type Vector.
observersList.elementAt(0) returns a Object, and for Object, userName isn't defined.

You have to cast the Object to Observer:
Code:
Observer tmp = (Observer) observersList.elementAt(0);
System.out.println (tmp.userName);

seeking a job as java-programmer in Berlin:
 
Thanks.

Why does

Code:
System.out.println(observersList.elementAt(0).getClass());

return observer then?
 
Because this forces the Object.toString() method to be called.

--------------------------------------------------
Free Database Connection Pooling Software
 
// try this
// may be getClass is method from object so it will not be change after it is stored and retrieved from vector
import java.util.*;
class test
{
public static void main(String args[])
{
Object o = new String("Jon");
System.out.println(o.getClass());

String s = new String("hello");
Vector v = new Vector();
v.add(s);
System.out.println(v.get(0).getClass());
}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top