Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my LinkedHashSet empty within the toString() method?

Tags:

java

tostring

I have a simple class extending LinkedHashSet and am trying to override the toString() method. I've added some elements to the Set in the main method, however within my toString method, the Set is empty. The code:

import java.util.*;
import java.util.*;

public class MyHashSet<T> extends LinkedHashSet<T>{
    private Set <T> myHashSet;


    public MyHashSet (){
        myHashSet = new HashSet<T>(5);
    }

    @Override
    public String toString(){
         if (myHashSet.isEmpty())
            return "This MyHashSet is empty.";
         else
            return myHashSet.toString();
    }

    public static void main (String[] args){
         MyHashSet <String> myHashSet = new MyHashSet<>();

         myHashSet.add("A");
         myHashSet.add("B");
         myHashSet.add("C");
         myHashSet.add("D");
         myHashSet.add("E");

         System.out.println(myHashSet);

         System.out.println(myHashSet.isEmpty());
    }
}

returns the following:

This MyHashSet is empty.
false

I'm expecting toString() to instead return

[A, B, C, D, E]

What am I doing wrong? Thanks in advance.

like image 752
Lisa S Avatar asked Dec 12 '25 07:12

Lisa S


1 Answers

The toString() method relies on the myHashSet field you are declaring but you don't add elements in .

Indeed, here :

     MyHashSet <String> myHashSet = new MyHashSet<>();

     myHashSet.add("A");
     myHashSet.add("B");
     myHashSet.add("C");
     myHashSet.add("D");
     myHashSet.add("E");

You add the elements by relying on the LinkedHashSet implementation that your class inherits from. And it of course doesn't use your field.

In fact, you don't even need declare myHashSet if you extend LinkedHashSet.
So just the change the toString() method to rely on the class you inherit from :

@Override
public String toString(){
     if (isEmpty())
        return "This MyHashSet is empty.";
     else
        return super.toString();
}

Otherwise you can also use composition by relying on the myHashSet field but so you should not extend LinkedHashSet but rather implement Set<E>.

Anyway, use inheritance or composition.
But not both at the same time.

like image 82
davidxxx Avatar answered Dec 13 '25 20:12

davidxxx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!