You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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 List interface, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 10:10:08