简体   繁体   English

如何在对象中存储Set / HashSet?

[英]How do I store Set/HashSet in Object?

 public HashSet<String> Red;
 public HashSet<String> Blue;
 public HashSet<String> Colors;

public Data(HashSet<String> red, HashSet<String> blue, HashSet<String> colors) {
  Red = red;
  Blue = blue;
  Colors = colors;
}

I try to store 3 Set / HashSet inside this Object. 我尝试在此对象中存储3 Set / HashSet。 Is this way to correct way, could I acces due the object the Set/HashSet, like normal ones: 这是正确的方法吗,我是否可以像正常对象一样访问对象的Set / HashSet:

public Set<String> Red = new HashSet<String>();

If you are asking how to access the HashMap s inside your Data object 如果您询问如何访问Data对象中的HashMap

To access one of the three HashSets, you would create a new Data object and access the public field of choice after the Data object has been initialized: 要访问三个HashSet之一,您将创建一个新的Data对象并在初始化Data对象后访问选择的公共字段:

HashSet<String> setOne = new HashSet<String>();
HashSet<String> setTwo = new HashSet<String>();
HashSet<String> setThree = new HashSet<String>();

Data d = new Data(setOne, setTwo, setThree);
d.Blue.add("this will be added to setTwo");

Normally however, you would want not to have public fields, but instead make them private and provide getter/setter methods, as this will provide encapsulation . 但是,通常情况下,您不希望拥有公共字段,而是将它们设为私有并提供getter / setter方法,因为这将提供封装

If you are asking whether you should refer to the interface or class 如果您在询问是否应该引用接口或类

First: HashSet is a concrete class and Set is an interface. 首先: HashSet是一个具体的类,而Set是一个接口。 Also: The reference type decides what methods you can call upon an object. 另外: 引用类型决定可以对对象调用的方法。 (This would be the left side of the equals sign, while the right side is the dynamic type). (这是等号的左侧,而右侧是动态类型)。

In the constructor you would want to be the least specific as possible. 在构造函数中,您将希望尽可能地不具体。 Are you not using any special functionality of the HashSet class, you should favour referring to the Set interface, as this is much more flexible should you want to change implementation of the Data class later on - it also makes it possible for users of your class to use every class that implements Set rather than to be restricted of using the HashSet. 如果您没有使用HashSet类的任何特殊功能,则应优先参考Set接口,因为如果以后要更改Data类的实现,此接口将更加灵活-这也使类的用户有可能使用实现Set的每个类,而不是被限制使用HashSet。

Do you however need special functionality of a specific class, you would of course then refer to that class. 但是,您是否需要特定类的特殊功能,那么您当然会引用该类。

如果我理解正确,您是否在问是否允许Set<String> Red = new HashSet<String>()HashSet<String> Red = new HashSet<String>()

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

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