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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With