1

I have the following code and I wish to know if that is the correct way to return the Array. my function returns Page<byte[]>[] (an Array of Page<byte[]>), and I'm using ArrayList as the container.

pages is a private HashMap member. Page is an object I created that have a member of a generic type T.

in the end I return my ArrayList casted with toArray, but I can't just tell it to cast it to Page array object, it needs a fixed size (new Page[pageArray.size()]) and I think that this is not the right way to do that.

What is right way?

public Page<byte[]>[] getPages(Integer[] pageIds){
    ArrayList<Page<byte[]>> pageArray = new ArrayList<Page<byte[]>>();
    for (int pageId : pageIds){
        if (pages.containsKey(pageId)){
            pageArray.add(pages.get(pageId));
        }
    }
    return pageArray.toArray(new Page[pageArray.size()]);
    //return pageArray.toArray(Page);
YSY
  • 1,096
  • 2
  • 12
  • 19

3 Answers3

1

I can't understand why you are using arrays instead of lists if you have to perform such operations on them.

Anyway your method is right and does the work. Another approach without using ArrayList can be this one:

public Page<byte[]>[] getPages(Integer[] pageIds){
    int count = 0;
    for (int i=0; i<pageIds.length;i++){
        if (pages.containsKey(pageIds[i])){
            count++;
            pageIds[i] = -1; //BEWARE! this modifies the original pageIds array!
        }
    }
    int retCount = 0;
    Page<byte[]>[] ret = new Page<byte[]>[count];
    for (int i=0; i<pageIds.length;i++){
        if(pageIds[i]!=-1){
            ret[retCount] = pages.get(pageIds[i]);
            retCount++;
        }
    }
    return ret;
}

But it really doesn't add anything to your method...

Narmer
  • 1,386
  • 6
  • 16
0

This should work:

    @SuppressWarnings("unchecked")
    public Page<byte[]>[] getPages(Integer[] pageIds) {

      final ArrayList<Page<byte[]>> pageArray = new ArrayList<Page<byte[]>>();

      for (int pageId : pageIds) {
        if (pages.containsKey(pageId)) {
          pageArray.add(pages.get(pageId));
        }
      }

      return pageArray.toArray(new Page[pageArray.size()]);
    }
Cristian Sulea
  • 254
  • 1
  • 6
-1

I would suggest to use an empty parameter since that way you don't create any large temporary object:

return pageArray.toArray(new Page[0]);

size is determined by the size of the pageArray anyway.

Eypros
  • 4,362
  • 5
  • 29
  • 46
  • Well the "large" array needs to be crated anyway, your solution only makes 1 more objects. If `toArray()` receives large enough array, it will store the result in that array, *otherwise* a new array is created. [javadoc](http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#toArray(T[])) – kajacx Sep 05 '14 at 09:04