如何将MongoDB的BasicDBList转换为Java ArrayList?
How to Convert BasicDBList to ArrayList<String[]> in Java
Let's fix your issue step by step. The error you're seeing happens because main1.get("Data") returns a BasicDBList (a MongoDB-specific list implementation), not a single String[] array. You can't cast the entire list directly to a string array—you need to iterate through the BasicDBList and convert each element to String[] individually.
Here's the corrected code:
DBCursor cursor1 = coll2.find(); DBObject main1 = cursor1.next(); // First, retrieve the BasicDBList from your DBObject BasicDBList dataList = (BasicDBList) main1.get("Data"); ArrayList<String[]> ans = new ArrayList<>(); // Iterate through each item in the BasicDBList for (Object item : dataList) { // Handle the case where each item is another BasicDBList (common in MongoDB) if (item instanceof BasicDBList) { BasicDBList subList = (BasicDBList) item; // Convert the sub-BasicDBList to a String array String[] strArray = subList.toArray(new String[subList.size()]); ans.add(strArray); } // If some items are already String arrays, handle that too else if (item instanceof String[]) { ans.add((String[]) item); } }
Why your original code failed:
Your line ans.add(((String[]) main1.get("Data"))); tries to cast the entire BasicDBList (which is a collection of items) to a single String[], which is a type mismatch. The ClassCastException is MongoDB telling you that these two types are fundamentally incompatible.
Extra Notes:
- BasicDBList implements the standard Java
Listinterface, so you can also use it directly in many cases without converting to ArrayList. But if you specifically need an ArrayList, the above approach works perfectly. - Adjust the inner conversion logic if your "Data" field contains non-BasicDBList elements (e.g., if items are DBObjects that need custom parsing into String arrays).
内容的提问来源于stack exchange,提问作者Muhammad Rafique
相关产品推荐
相关产品推荐

