0

I do have such piece of code:

List<VersionedUserIdentifier> userIdentifiers = getUsersModule().getUsersIdentifiers();
if (userIdentifiers.isEmpty()) {
    LOG.info(No users to verify.");
    return;
}
VersionedUserIdentifier[] vIds = userIdentifiers.toArray(new VersionedUserIdentifier[0]);

I'm getting an error:

java.lang.ArrayStoreException
at java.util.ArrayList.toArray(ArrayList.java:133)

I cannot convert list to array. Any ideas what could be wrong? I have also tried:

VersionedUserIdentifier[] vIds = userIdentifiers.toArray(new VersionedUserIdentifier[userIdentifiers.size()]);
Maciaz
  • 1,084
  • 1
  • 16
  • 31
  • `new VersionedUserIdentifier[0]` can you explain this? – Danyal Sandeelo May 02 '19 at 12:19
  • `LOG.info(No users to verify.");` correct this one too – Danyal Sandeelo May 02 '19 at 12:20
  • Try this [Convert ArrayList to String[] array [duplicate]](https://stackoverflow.com/questions/5374311/convert-arrayliststring-to-string-array) or [Converting 'ArrayList to 'String\[\]' in Java](https://stackoverflow.com/questions/4042434/converting-arrayliststring-to-string-in-java) – Butiri Dan May 02 '19 at 12:21
  • @DanyalSandeelo: The `new VersionedUserIdentifier[0]` is correct. – Nikolas Charalambidis May 02 '19 at 12:24
  • `toArray` is same as `toArray(new Object[0]) ` just read it. Thanks @Nikolas – Danyal Sandeelo May 02 '19 at 12:25
  • @Maciaz Can you provide a complete example so that we can compile it and reproduce the error? – marstran May 02 '19 at 12:28
  • Unfortunatelly not. This is a part of bigger application. This was supposed to be just a simple ArrayList to Array convertion, but something goes wrong. `VersionedUserIdentifier` is a class with just 2 fields (id, version), standard getters, setters and constructor. – Maciaz May 02 '19 at 12:47

2 Answers2

1

This type of exception happens when you try to store different type of the object in the array.

Refer the below link Oracle doc

Rutvik Joshi
  • 97
  • 3
  • 13
  • The object type is exactly the same. – Maciaz May 02 '19 at 13:04
  • Still I concur with Rutvik Joshi: `getUsersIdentifiers` probably uses untyped conversions and does not contain the same class `VersionedUserIdentifier`: `if (!userIdentifiers.stream().allMatch(vui -> vui instanceOf VersionedUserIdentifier)) { brrr }`. **Maybe the class was introduced in two different packages.** – Joop Eggen May 02 '19 at 13:16
  • if untyped conversion is done internally as @JoopEggen described above try to typecasting it like VersionedUserIdentifier[] vIds = (VersionedUserIdentifier[]) userIdentifiers.toArray(new VersionedUserIdentifier[0]); – Rutvik Joshi May 02 '19 at 13:47
-1

This works for me..Please check

List<VersionedUserIdentifier> userIdentifiers = getUsersModule().getUsersIdentifiers();
VersionedUserIdentifier[] vui=(VersionedUserIdentifier[])userIdentifiers.toArray();
Stream.of(vui).forEach(System.out :: println);
SRK
  • 135
  • 8