help in class type converstion

  • Thread starter Thread starter Cheryl
  • Start date Start date
C

Cheryl

I am trying to use ArrayList to implement a class Wordlist.

Wordlist wordlist;

public ListOfData()
{
wordlist = new ArrayList();
}

But then when I try to access the objects in the ArrayList, Object is
returned instead of type Wordlist. What should I do in order to access the
member functions of wordlist?
 
Cheryl said:
I am trying to use ArrayList to implement a class Wordlist.

Wordlist wordlist;

public ListOfData()
{
wordlist = new ArrayList();
}

That's not going to work to start with, as you've declared wordlist to
be of type Wordlist, not ArrayList.
But then when I try to access the objects in the ArrayList, Object is
returned instead of type Wordlist. What should I do in order to access the
member functions of wordlist?

Just cast when you retrieve the object, e.g.

Foo x = (Foo) myArrayList[0];
 
Vadym Stetsyak said:
inherit Wordlist from ArrayList and then just call wordlist = new
Wordlist();

In my experience there's rarely a good reason to inherit from
ArrayList. For strong typing, you'd use CollectionBase instead. For
most other purposes, it would be better to use composition rather than
inheritance.
 
Back
Top