Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
Generic array casting java?
I have an assignment where we are to create a LinkedList class from scratch, implementing a given interface. This interface gives us the method public E[] toArray()
I cannot get the casting to work, when I test in JUnit using Integer objects the cast fails.
I initialize my array as E[] array = (E[]) new Object[howManyINeed]
How do I get this to work?
It is in an assignment and other people have gotten it to function so obviously there is a way to do it
3 Answers
- husoskiLv 75 years ago
You can do that, but not without getting an unchecked cast warning. There way that Java generics are defined, there is no truly type-safe way to do this; which is why the expected syntax of "new E[size]" is specifically disallowed when E is a parameterized type.
Try running your code, despite the warning, and it should be okay.
One way to eliminate the warning is to use the @SuppressWarnings annotation before the constructor or method containing the problem, like:
@SuppressWarnings({"unchecked"})
public TheList(int n) {
data = (E[]) new Object[n];
}
See the full sample at:
- Anonymous5 years ago
no