Bag.getData() leads to ClassCastException
See original GitHub issueWith recent changes, it seems that Bag.getDate() used to return Object[], now it returns E[]. After running the test case below, a ClassCastException occurs due to the underlying array actually being an Object[] when the type is not specified through the constructor.
Cause
public Bag(int capacity) {
data = (E[])ArrayReflection.newInstance(Object.class, capacity);
}
Test Case
public class BagTest {
private Bag<Integer> intBag;
@Before
public void setup() {
intBag = new Bag<Integer>();
intBag.add(Integer.valueOf(1));
}
@Test
public void test_getData() {
Integer[] intArray = intBag.getData(); // <-- Exception happens here
for(Integer i : intArray) {
System.out.println(i);
}
}
}
Result
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer; at com.artemis.utils.BagTest.test_getData(BagTest.java:26)
Issue Analytics
- State:
- Created 7 years ago
- Comments:7 (4 by maintainers)
Top Results From Across the Web
Resolving ClassCastException in this code - Stack Overflow
I have this method getData as shown . It is expecting an array of bag Objects as shown please see the code below...
Read more >ClassCastException (Java SE 19 & JDK 19)
Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. For...
Read more >How to Solve ClassCastException in Java - Rollbar
When your code attempts to cast an object to another class of which the original object is not an instance, a ClassCastException is...
Read more >Explanation of ClassCastException in Java - Baeldung
ClassCastException is an unchecked exception that signals the code has attempted to cast a reference to a type of which it's not a...
Read more >How to fix java.lang.ClassCastException while using the ...
The java.lang.ClassCastException is one of the unchecked exception in Java. It can occur in our program when we tried to convert an object ......
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
what am I doing, that was a terrible idea… reverting previously attempted fix
Cool.