简体   繁体   English

Java:HashSet 多种类型

[英]Java: HashSet multiple types

I have a program that I have to use a HashSet for.我有一个必须使用 HashSet 的程序。 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.我的问题源于这样一个事实,即 HashSets 主要包含一个对象,但如果我希望将信息发送到另一个类,它需要三个对象:一个字符串、一个整数和一个布尔值。 The assignment says that I must use a HashSet作业说我必须使用 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 .我有一个类应该发送包含namesizeisVisible的咒语集。

Magic.go() class: Magic.go() 类:

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

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;
    }
}

You can use a HashSet that stores Objects.您可以使用存储对象的 HashSet。 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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM