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

我尝试在此对象中存储 3 个 Set / HashSet。这种方式是否正确,我可以像普通对象一样访问 Set/HashSet 对象吗?

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

2 回答 2

1

如果您询问如何访问对象HashMap内的 sData

要访问三个 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");

但是,通常,您不希望有公共字段,而是将它们设为私有并提供 getter/setter 方法,因为这将提供封装

如果您问是否应该参考接口或类

首先:HashSet 是一个具体的类,Set 是一个接口。 另外:引用类型决定了您可以在对象上调用哪些方法。(这将是等号的左侧,而右侧是动态类型)。

在构造函数中,您希望尽可能不具体。您是否没有使用 HashSet 类的任何特殊功能,您应该倾向于引用 Set 接口,因为如果您以后想更改 Data 类的实现,这会更加灵活 - 它也使您的类的用户成为可能使用每个实现 Set 的类,而不是限制使用 HashSet。

但是,您是否需要特定类的特殊功能,那么您当然会参考该类。

于 2012-10-31T16:56:20.737 回答
0

如果我的理解是正确的,你是在问两者Set<String> Red = new HashSet<String>()是否HashSet<String> Red = new HashSet<String>()都是允许的形式?

于 2012-10-31T14:20:41.710 回答