1

I have a LinkedHashMap of pages, and I have an array of PageIDs. I want to write a method that returns an array of the pages whos id is found in PageIDs

the problem is that page is a generic class.

when I write Page<byte[]>[] pagesToReturn = new Page<byte[]>[pageIds.length]; I ofcourse get the error "Cannot create a generic array of Page".

When I try to create an array and then cast it, as such: Page<byte[]>[] pagesToReturn = (Page<byte[]>[]) new Page[pageIds.length]; I get a warning "Type safety: Unchecked cast from Page[] to Page[]".

I know this is somewhat of a delicate issue, but I have to adhere to the signature of the method public Page<byte[]>[] getPages(Long[] pageIds), it has to return an array of pages whos generic type is array of bytes.

Is there a workaround to this issue that does not include a warning supression?

6
  • 1
    "I have to adhere to the signature" is your real problem. The decision by the brain surgeon who threw generic and arrays together should be overturned and the method signature changed to return a list instead of an array. Commented Mar 26, 2016 at 13:42
  • @Bohemian That's not my call. This is for a university project. We aren't being awarded bonus points for changing the instructions. Commented Mar 26, 2016 at 13:48
  • You can check manually that the cast is safe, then suppress the warning with an annotation. It's the best you can do in a bad situation. Commented Mar 26, 2016 at 13:52
  • @Oria well you would be very unlikely to find such a signature in real life commercial code Commented Mar 26, 2016 at 13:54
  • @Bohemian Good thing too. I'll just supress the warning for now, and I'll ask the professor if that's okay. If not, I'll ask him for further instructions. Thanks everyone. Closing this question. Commented Mar 26, 2016 at 13:55

2 Answers 2

2

Is there a workaround to this issue that does not include a warning supression?

There isn't. But, if everywhere else in the program you paid attention to type safety, and therefore the array of Page is guaranteed to contain instances of Page<byte[]>, then this cast is safe.

The best way to handle this situation is to suppress the warning, and add a comment explaining that the cast is safe, because you know that the elements are guaranteed to be the correct type.

Sign up to request clarification or add additional context in comments.

Comments

1

Suppressing the warning as follows:

@SuppressWarning("unchecked")
Page<byte[]>[] pagesToReturn = (Page<byte[]>[]) new Page[pageIds.length];

you can also do the following:

public class MyPage extends Page<byte[]>{
...
}

MyPage[] pagesToReturn = new MyPage[pageIds.length];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.