blz
blz

Reputation: 414

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.

Upvotes: 1

Views: 201

Answers (1)

Vasu
Vasu

Reputation: 22422

Yes, in your current code, linkedList inside Bucket class does not point to any object, so it throws java.lang.NullPointerException, so to solve the issue, you can follow the below approach:

Basically, a LinkedList IS-A Collection, so you can simply typecast collection object (from super class Class1) to linkedList object and return the first element as shown below:

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

    public Bucket(){
        super(new LinkedList<String>()); 
        //now typecast and assign collection to linkedList
        linkedList = (LinkedList<String>)collection;
    }

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

Upvotes: 2

Related Questions