Jump to content

LinkedList of Objects?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
dabbler

dabbler

    Newbie

  • Members
  • Pip
  • 1 posts
Hi I had a quick question. Can the LinkedList in util be used to form a List of any objects, including instances of classes I create? How would I do that?

#2
John

John

    Writes binary right handed and hex left handed

  • Moderators
  • 6,321 posts
I believe any lists can be used to hold any data type, ATD's or objects. I don't have eclipse on my computer at the moment, but to use it, it should be the same as adding any item to the list.

#3
mungojelly

mungojelly

    Newbie

  • Members
  • Pip
  • 1 posts
Hello, I'm new to Java as well, so I'm happy to be able to answer your question. :)

You can make a LinkedList to hold any kind of object, including classes you've made yourself. If you've made a class named Foo, then you can make a new LinkedList of Foo objects like this:


LinkedList<Foo> listOfFoos = new LinkedList<Foo>();

The first part, "LinkedList<Foo> listOfFoos", is a declaration of the name listOfFoos, declaring that it's of the type "a LinkedList set up to hold objects of type Foo." The second part, "new LinkedList<Foo>()", makes an actual object which is "a LinkedList set up to hold objects of type Foo." The object is plucked from the ether (that is, constructed) and a reference to it is associated with the name "listOfFoos". Now you can use that name to do anything that a LinkedList does:


listOfFoos.add(new Foo());

listOfFoos.removeLast();

if (listOfFoos.size() < 12) { ... }

I believe if you just say LinkedList without the < > you'll get a generic version that can hold anything. Another way to ask for a linked list that can hold anything is to say LinkedList<Object> -- that can hold anything which is an Object or a subclass of Object, aka everything.

HTH. :)

<3