繁体   English   中英

从Java中的接口定义的类中获取对象

[英]Get object from interface defined class in Java

我不确定如何用标题来描述这一点,我是Java的初学者,这里有一些示例代码:

我的目标类似于此问题: Java中两个对象包的并集 ,区别在于参数,此问题中提供的解决方案有一个T[] item ,在我的情况下,它是BagInterface<T> anotherBag

介面: http : //people.cs.pitt.edu/~ramirez/cs445/handouts/BagInterface.java

ArrayBag.java:在union()中,我希望将2个数据袋(数据集)中的所有项目加到1。

public class ArrayBag<T> implements BagInterface<T>
{
    private int length;
    ...
    /* union of 2 bags */
    public BagInterface<T> union(BagInterface<T> anotherBag) // This has to be stay like that.
    {
        int total = length + anotherBag.getSize();
        BagInterface<T> items = (T[]) new Object[total];  // this may be faulty

        for (int i = 0; i < length; i++)
            items.add(bag[i]);                            // bag is current bag

        for (int i = 0; i < anotherBag.getSize(); i++)    // this is definitely wrong
            items.add(anotherBag[i]);

        return items;
    }
}   

我该怎么解决?

您尚未提供完整的接口,但是您将需要使用BagInterface的实现来返回BagInterface。 更换

BagInterface<T> items = (T[]) new Object[total];

BagInterface<T> items = new ArrayBag();

或适用于ArrayBag类的适当构造函数(同样,您没有提供足够的代码让我知道)。 提供BagInterface有一个add(T)方法,这个方法应该可以工作,但是您还需要调整访问另一个包的方式。 我将假设您有一个名为bag的实例变量,它是T的数组。在这种情况下,将第二个循环中的add更改为:

items.add(anotherBag[i]);

items.add(anotherBag.bag[i]);

如果这没有帮助,请提供更多信息和上下文。

暂无
暂无

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

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