简体   繁体   English

ArrayList和Formatter表现异常

[英]ArrayList and Formatter not behaving as expected

I have two Arraylists, one contains an entire list of objects, the second contains objects to remove from the first list. 我有两个Arraylist,一个包含整个对象列表,第二个包含要从第一个列表中删除的对象。

When I remove the objects from the first list and when I output those objects to a file using a Formatter, nothing is written to the file. 当我从第一个列表中删除对象并且使用格式化程序将这些对象输出到文件时,没有任何内容写入该文件。 However if I output the objects from the first Arraylist, without removing any objects, all of those objects appear in the file. 但是,如果我从第一个Arraylist输出对象,而没有删除任何对象,则所有这些对象都会出现在文件中。

For example:- 例如:-

for(Invoice inv : tempStore)
{
  if(invoiceLines.contains(inv))invoiceLines.remove(inv);
}

//for each invoice in the ArrayList
for(Invoice invoice : invoiceLines)
{
  output.format("%"+this.spec.getLength("XXXX")+"s\t",checkString(invoice.getInvoiceDate()));}

gives me no output, however doing just:- 给我没有任何输出,但是只做:-

//for each invoice in the ArrayList
for(Invoice invoice : invoiceLines)
{
  output.format("%"+this.spec.getLength("XXXX")+"s\t",checkString(invoice.getInvoiceDate()));}

gives me output information, when manually debugging the application the arraylist (the one with the objects removed), does contain objects still and those objects contain the correct values. 给我输出信息,当手动调试应用程序时,arraylist(除去对象的那个)确实包含对象,并且这些对象包含正确的值。 It's almost as if the Arraylist, once objects are removed is losing the pointers in memory. 一旦删除对象,就好像Arraylist失去了内存中的指针一样。

Any ideas? 有任何想法吗? Unfortunately I can't give much in the way of specific code, however ask any questions and I will try to answer as best as I can. 不幸的是,我对特定代码的处理方式不多,但是提出任何问题,我将尽力回答。 The language is Java and I'm using Java compliance 1.5 in the SDK. 语言是Java,我在SDK中使用的是Java规范1.5。

To identify the error you can add more output (as console output or using a Logger) on the removing operation: 要确定错误,可以在删除操作上添加更多输出(作为控制台输出或使用Logger):

System.out.println("Items before removal: " + invoiceLines.size());
for(Invoice inv : tempStore)
{
  if(invoiceLines.contains(inv)) {
    invoiceLines.remove(inv);
    System.out.println("removed " + inv + ". Items left: " + invoiceLines.size());
  }    

} 

If there are more than items removed during one iteration, you want to check the equals() and hashCode() Implementation of the Invoice class. 如果在一次迭代中删除的项目不止一个,则需要检查Invoice类的equals()和hashCode()实现。 If you have your own implementation, make sure you followed the Object.equals()-Contract . 如果您有自己的实现,请确保遵循Object.equals()-Contract

在输出末尾需要调用Formatter.flush()Formatter.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM