How to use Linkedhashset to implement this Ihashset interface?

Asked

Viewed 40 times

0

How to use LinkedHashSet implementing the interface IHashSet using chain to resolve conflicts and with load factor 0.75?

//Usando essa interface
public interface IHashSet{
 public void put(Object data);
 public boolean contains(Object data);
 public void remove(Object data);
 public boolean isEmpty();
 public int size();
}
  • Why do you want to do this? Class LinkedHashSet already does exactly that, so it seems to me that you are looking for something in that style, but you shouldn’t be wanting something like this for no good reason.

1 answer

2

First, it would be a good idea to make this interface generic:

public interface IHashSet<E> {
    public void put(E data);
    public boolean contains(E data);
    public void remove(E data);
    public boolean isEmpty();
    public int size();
}

All these methods already exist in the LinkedHashSet, which by default already uses chaining to resolve conflicts (collision of hashes) and already 0.75 has as the standard load factor. So just delegate the calls:

import java.util.LinkedHashSet;

public class MyHashSet<E> implements IHashSet<E> {
    private final LinkedHashSet<E> set;

    public MyHashSet() {
        set = new LinkedHashSet<>();
    }

    @Override
    public void put(E data) {
        set.add(data);
    }

    @Override
    public boolean contains(E data) {
        return set.contains(data);
    }

    @Override
    public void remove(E data) {
        set.remove(data);
    }

    @Override
    public boolean isEmpty() {
        return set.isEmpty();
    }

    @Override
    public int size() {
        return set.size();
    }
}

However, I question why you do it. Unless you have a very good reason (I’m sure there are some, but I have my doubts in this case), there’s not much point in doing it. The interface IHashSet is an attempt to reinvent the square wheel and the implementation I gave only uses the standard round wheel to make a square wheel. The ideal would be simply to use the interface java.util.Set standard and implementation java.util.LinkedHashSet standard, and with that you wouldn’t need to IHashSet nor the implementation thereof.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.