0

I am not sure how to describe this in title, I am a beginner of Java, here is a little sample code:

My target is similar to this question: Union of two object bags in Java, the difference is in the parameter, the solution provided in this question has a T[] item, in my case, it is BagInterface<T> anotherBag

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

ArrayBag.java: in union(), I wish to add all items up in the 2 bags (sets of data) to 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;
    }
}   

What can I do to solve this?

Community
  • 1
  • 1
hlx98007
  • 241
  • 5
  • 15
  • can you replace the `...` with the contents of the interface? I agree that the "may be faulty" line is probably wrong, but it's impossible to suggest corrections without the rest of the interface specification. – jedwards Jan 18 '14 at 21:54
  • @jedwards This is part of one of my homework solution so I could not show all of my work here. I have updated some information about this, please take a look at it. – hlx98007 Jan 18 '14 at 22:12
  • Do you want to add without duplication, or simply add all regardless? – Bohemian Jan 19 '14 at 02:39
  • @Bohemian Hi, with duplication. The interface did not provide getEntryAt(int index) method. – hlx98007 Jan 19 '14 at 11:46

1 Answers1

0

You have not provided the full interface however you will need to use an implementation of BagInterface to return a BagInterface. Replace

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

With

BagInterface<T> items = new ArrayBag();

or whatever the appropriate constructor for your ArrayBag class is (again, you have not provided enough code for me to know). Providing BagInterface has an add(T) method this should work, however you will also need to adjust how you are accessing the anotherBag. I am going to assume that you have an instance variable called bag which is an array of T. In this case, change the add in the second loop from:

items.add(anotherBag[i]);

to

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

If this is not helpful please provide more information and context.

flungo
  • 1,050
  • 1
  • 7
  • 21