vendredi 28 avril 2017

How to wrap a Collection object of a subclass?

I'm building an array where each element in the array is a LinkedList of Strings. I MUST use the following implementation:

Build a class that wraps a LinkedList object (and also extends a given class), and have every element in the array be an instance of this class. I'm given the following class which I need to extend (which I can't change, and I MUST use):

public Class1{
java.util.Collection<java.lang.String> collection;

    Class1(java.util.Collection<java.lang.String> collection){
        this.collection = collection; }

    public void add(String str) {
        collection.add(str); }

and Class1 has a couple more methods related to Collection (delete, etc.). I want to create a class that extends Class1, and wraps a LinkedList object. I want this class to meet two requirements:

  1. use Class1 implementation for the collection methods (add, delete, etc.)
  2. to have other methods of its own, for example the following getFirst() method.

So here's what I did:

public class Bucket extends Class1 {
    LinkedList<String> linkedList;

    Bucket(){
        super(new LinkedList<String>()); }

    public String getFirst(){
        linkedList.getFirst(); } }

I have a main class that tries to run the following code

Bucket bucket = new Bucket();
        bucket.add("5");
        bucket.getFirst();

This falls in the bucket.getFirst() line, because obviously the linkedList in the Bucket class is null, it isn't the LinkedList object I've sent to Class1, so the getFirst() method in Bucket is trying to operate on null.

How can I solve this? How can I connect the LinkedList I send to Class1 to the LinkedList I have in the Bucket class? Thank you for reading so far.

Aucun commentaire:

Enregistrer un commentaire