在java中连接每个维度d的n个arraylist的错误

时间:2012-04-21 16:59:56

标签: java debugging arraylist

我想将N个数量的d维arraylist连接成一个大的arraylist。我做了以下事情:

 {
     Arraylist<Double> cFeature = new Arraylist<Double>(); 
     for(int i =0 ; i < n; i++){
        ArrayList<Double> arrList = new ArrayList<Double>();
        arrList = FeatureMatrix.get(i);
        cFeature.addAll(arrList);
     }  
    return cFeature;
}

但这并没有让我重新连接特征向量。可能是什么原因?

我有以下类型的矩阵

    1 2 3 4
    4 5 6 7
    9 4 5 2

我想要返回类似的内容:

    12344567, 45679452 etc

编辑[矩阵一行],矩阵维度为50

   [-1.4707351089135285, -2.396807707665656, -0.9225858560474335, -0.552093667789784, 0.6492206869123566, 1.1347653279780474, 0.18599226559979623, -0.3040490372134513, -0.8661743997164002, 1.2990217001062885, -1.4689261255216413, -0.6175058675322327, 0.0019875740898560707, 3.187991109660048, 0.9793588130569899, 1.88726260031087, 1.263110196592273, 0.10270882950413489, -0.33850097448844163, 0.26780865103769547, -0.28117099016766645, -0.015511886681809741, -0.7906057240014217, 0.1796874905794462, 0.9327631100459427, 0.5419684468033518, 1.3670537985364393, -1.0381888770019032, 1.0975151287297011, 0.024367745998744996, -0.25780912155025204, -1.862325174655491, -0.611104255824939, -0.5746070435381269, -1.2218773341433158, 0.2220916817954159, 0.4641455500389115, -0.43253367269335635, -0.5380163044326588, 0.685592907063921, -0.6191939669845238, -1.2275198581496152, 0.13270110767423787, -0.1614948461888469, 1.5717904793822337, -0.2826323802880358, -0.4716922630198008, -0.2881374794211655, 0.8609910302314909, 1.1749707572533885]

1 个答案:

答案 0 :(得分:1)

您在问题中省略了代码的关键部分。看看the chatfull code on pastebin在我看来问题是你不明白赋值如何在Java中工作(也许你有C ++背景?)

    ArrayList<Double> contextFeature = new ArrayList<Double>();
    contextFeature = wordFeatureMatrix.get(x); // x is a valid integer key, actually FrequentWordIndex.get(Ngram.get(0).toLowerCase()) in the pastebin code

这会破坏您为contextFeature创建的原始ArrayList,并将其替换为wordFeatureMatrix中的一个ArrayLists。

之后你不再迭代wordFeatureMatrix而是一个将索引返回到wordFeatureMatrix的列表。我有信心在某些时候

wordFeatureMatrix.get(FrequentWordIndex.get(Ngram.get(0).toLowerCase())) ==
    wordFeatureMatrix.get(FrequentWordIndex.get(Ngram.get(i).toLowerCase()));

这意味着以后你实际上是在打电话

 contextFeature.addAll(contextFeature);

来自ArrayList.addAll()的JavaDoc:

  

如果在操作过程中修改了指定的Collection,则此操作的行为是不确定的。 (这意味着如果指定的Collection是此列表,则此调用的行为是未定义的,并且此列表是非空的。)

所以,你有两个问题。第一个是在收集要替换解决方案的wordFeatureMatrix列表的过程中不修改contextFeature

    ArrayList<Double> contextFeature = new ArrayList<Double>();
    contextFeature = wordFeatureMatrix.get(x); 

    ArrayList<Double> contextFeature = new ArrayList<Double>();
    contextFeature.addAll(wordFeatureMatrix.get(x)); 

第二个问题,在您的用例中可能不是问题,是确保相同的列表不会被添加两次。这取决于你决定它是否是你想要的。