Java: HashSet multiple types

4.1k views Asked by At

I have a program that I have to use a HashSet for. My question arises from the fact that HashSets mainly contain one object, but if I wish to send information to the other class, it takes three objects: one string, one int, and one boolean. The assignment says that I must use a HashSet

Constructor I am trying to send information to:

public Magic (String name, int size, boolean isVisible)

I have a class that is supposed to be sending sets of spells containing name, size, and isVisible.

Magic.go() class:

public void go()
{
    int i = 0;
    while (i < size) {
        if (isVisible == true) {
            System.out.println(name + "!");
        }
        i++;
    }
} 
2

There are 2 answers

4
Tagir Valeev On

Just create an object which contains all the three fields like this:

import java.util.Objects;

public class NameSizeVisible {
    private final String name;
    private final int size;
    private final boolean isVisible;

    public NameSizeVisible(String name, int size, boolean isVisible) {
        this.name = name;
        this.size = size;
        this.isVisible = isVisible;
    }


    public String getName() {
        return name;
    }

    public int getSize() {
        return size;
    }

    public boolean isVisible() {
        return isVisible;
    }

    @Override
    public int hashCode() {
        return Objects.hash(name,size,isVisible);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        NameSizeVisible other = (NameSizeVisible) obj;
        if (isVisible != other.isVisible)
            return false;
        if (!Objects.equals(name, other.name))
            return false;
        if (size != other.size)
            return false;
        return true;
    }
}
2
user3354059 On

You can use a HashSet that stores Objects. So you would have:

HashSet<Object> set = new HashSet<>();
set.add(name);
set.add(size);
set.add(isVisible);

Then when you access the objects you just need to cast them to their respective types:

String name = "";
int size = 0;
boolean isVisible = false;

for (Object o : set) {
    if (o instanceof String) {
        name = (String) o;
    } else if (o instanceof int) {
        size = (int) o;
    } else {
        isVisible = (boolean) o;
    }
}