【发布时间】:2016-05-16 04:50:30
【问题描述】:
当我尝试使用还包含generics 的类的方法(这两个类都实现了接口)时,我遇到了严重的断开连接。我有一个SetInterface 接口,其中包含我的Set 类的方法。我的ProfileInterface 接口和Profile 类也是如此。在我的 Profile 类中,我有以下引用 Set 类的类型转换:
private Set<ProfileInterface> followBag = new Set<ProfileInterface>();
基本上,我们在我的数据结构课程中学习Array Bags、Linked Bags 等。我的问题是我希望在我的Profile 类到Composition 中使用Set 数据结构类的方法。我遇到的一个问题是我需要在我的Profile 类中创建一个方法,该方法交叉引用给定数组中的项目,以查看该Profile 对象是否“跟随”另一个Profile,如果不是,建议遵循该对象(任务是使用数据结构完成类似于 Twitter 或 Facebook 的事情)。这是我到目前为止创建的方法以及我无法通过的错误(从顶部开始的第三行):
public ProfileInterface recommend(){
ProfileInterface recommended;
ProfileInterface thisProfile = new Profile(); // <--Here is the question
for(int index = 0; index < followBag.getCurrentSize(); index++){
ProfileInterface follows = followBag[index];
for(int followedFollowers = 0; followedFollowers < follows.getCurrentSize(); followedFollowers++) { // <--Question here also
//if Profile's match, do nothing
//if Profile's do not match, set recommended == the Profile
}
}
return recommended;
}
请原谅我仍在处理的伪代码。但是我不能继续使用这种方法,直到我完全理解我需要做什么才能使第三个演员正确并了解我的其他问题(第二个注释)是否可能。
我在我的第二类 Java 中,我似乎无法通过这些问题。理想情况下,我希望一个成员或多个成员可以将其降低到 5 岁的水平,这样我就可以完全掌握它。我知道Profile 班级将与我的Set 班级有“有”关系(Composition)。我也知道,因为我已经按照我的方式投射了我的followBag,所以它可以同时使用ProfileInterface 和Set 方法。但是我想解释一下,如果可能的话,用例子来说明我如何在一个方法中正确地键入 cast 来获取数组的一个项目,或者在这个例子中我的 Set 中,并将其转换为给定的对象?我希望将此对象(在本例中为thisProfile)填充到给定索引以进行比较。但有两点我需要澄清:
A) 如下类型转换的对象会发生什么:
ProfileInterface thisProfile = new Profile();
既然我指的是接口和实现它的类?意思是,如果我的Profile() 类中有更多方法,那么这个thisProfile 只能访问哪些方法;接口还是类?
B) 我是否应该简单地调用ProfileInterface thisProfile,然后将thisProfile 的引用分配给我的内部for 循环中的特定索引?
C) 我的第二个注释:我在 IntelliJ 中收到一个错误,指出它是“cannot resolve method getCurrentSize()”。我不明白这一点,因为我在上面创建了follows 一行。我认为ProfileInterface follows = followBag[index] 会将给定的数组的Profile 索引设置为等于稍后在我的代码中使用的索引。这个错误源于我上面的困惑。因此,一旦我清楚地说明我做错了什么,我就会很肯定,我相信我会适当地解决它。
谢谢大家,我一如既往地期待听到您的回复!
【问题讨论】:
标签: java generics casting composition bag