【问题标题】:add and get String Array into and from Arraylist在 Arraylist 中添加和获取字符串数组
【发布时间】:2012-06-27 20:06:14
【问题描述】:

我有这个从 XML 文件中读取的代码。它获取五个字符串(groupId、groupType、filePath、author 和 lineNo),并首先将它们保存在一个字符串数组中。然后,字符串数组被保存在一个 ArrayList 中。最后,最后一个“for”显示了ArrayList的内容。

当我想显示内容时,我只得到最后添加的字符串数组的问题。以下是代码和输出。谁能弄清楚是什么问题?

ArrayList<String[]> developerTypes = new ArrayList<String[]>();
String[] developerInfo = {null, null, null, null, null};
String[] developerInfoR = {null, null, null, null, null};

String groupId;
String groupType;
String filePath;
String author;
String lineNo;


SAXBuilder builder = new SAXBuilder();
Document doc = (Document) builder.build("A.xml");
Element clones = doc.getRootElement();

// Loop of clones' children (clone_group)
List<Element> parentElements = clones.getChildren();
for(Element parentElement:parentElements){


    // Loop of clone_group's children (clone_fragment)
    List<Element> elements = parentElement.getChildren();
    for(Element element:elements){

        // Loop of clone_fragment's children (blameInfo)
        List<Element> childelements = element.getChildren();
        for(Element childElement:childelements){

            groupId = parentElement.getAttributeValue("groupid");
            groupType = parentElement.getAttributeValue("type");
            filePath = element.getAttributeValue("file");
            author = childElement.getAttributeValue("author");
            lineNo = childElement.getAttributeValue("lineNo");
            //System.out.print(groupId + " - ");
            //System.out.print(groupType + " - ");
            //System.out.print(file + " - ");
            //System.out.println(author);
            developerInfo[0] = groupId;
            developerInfo[1] = groupType;
            developerInfo[2] = filePath.substring(1, filePath.lastIndexOf("."));;
            developerInfo[3] = author;
            developerInfo[4] = lineNo;
            developerTypes.add(developerInfo);

        }// for (blameInfo)    
    }// for (clone_fragment)
}// for (clone_group)

// Display the content of the Arraylist    
for(int i = 0; i< developerTypes.size(); ++i){

    developerInfoR = developerTypes.get(i);

    for(int j = 0; j< developerInfoR.length; ++j){

        System.out.print(developerInfoR[j] + " ");

    }
    System.out.print("\n");

}

输出:

309 Type-3 builtin/update-index.c Jonathan Nieder 704 
309 Type-3 builtin/update-index.c Jonathan Nieder 704 
309 Type-3 builtin/update-index.c Jonathan Nieder 704 
309 Type-3 builtin/update-index.c Jonathan Nieder 704 
309 Type-3 builtin/update-index.c Jonathan Nieder 704 
309 Type-3 builtin/update-index.c Jonathan Nieder 704 
309 Type-3 builtin/update-index.c Jonathan Nieder 704 
309 Type-3 builtin/update-index.c Jonathan Nieder 704 
309 Type-3 builtin/update-index.c Jonathan Nieder 704 
309 Type-3 builtin/update-index.c Jonathan Nieder 704 
309 Type-3 builtin/update-index.c Jonathan Nieder 704 
309 Type-3 builtin/update-index.c Jonathan Nieder 704 
...

【问题讨论】:

  • 在我看来,您需要知道如何使用调试器处理好的 IDE,当您“单步执行”这样的代码时,错误会很快显现出来。

标签: java arraylist


【解决方案1】:

当我想显示内容时,我只得到最后添加的字符串数组的问题。

不,您发现您有 许多same 字符串数组的引用...因为那是您添加的内容。你只有一个字符串数组 object; developerInfo 只是对该数组的引用。当您调用 developerTypes.add(developerInfo) 时,会将引用复制到 ArrayList,因此您多次获得相同的引用。

您应该将developerInfo 的声明和实例化拉入循环:

String[] developerInfo = {
    groupId,
    groupType,
    filePath.substring(1, filePath.lastIndexOf(".")),
    author,
    lineNo
};
developerTypes.add(developerInfo);

同样,如果您在使用之前不声明 developerInfoR,您的代码会更简洁:

for(int i = 0; i< developerTypes.size(); ++i){
    String[] developerInfoR = developerTypes.get(i);
    for(int j = 0; j< developerInfoR.length; ++j){
        System.out.print(developerInfoR[j] + " ");
    }
    System.out.print("\n");
}

或者更好的是,使用增强的 for 循环:

for (String[] developerInfoR : developerTypes) {
    for (String info : developerInfoR) {
        System.out.print(info + " ");
    }
    System.out.print("\n");
}

一般而言,您应该尽可能晚地声明具有最小范围的局部变量,理想情况下在声明时分配一个值。在方法的顶部声明所有变量确实会损害可读性。

【讨论】:

  • 这也使得识别 C 程序员变得非常容易。
  • @Charles 请注意,不是任何 C 程序员,而是 K&R 风格的 C 程序员 :)
【解决方案2】:

您只有一个 developerInfo 数组实例,您在循环中不断地添加它。您需要在每个循环步骤中创建一个新数组。

您似乎对您正在使用的结构的语义有一些误解。我从您预先初始化developerInfoR 的方式推断出这一点,但从不使用该值。数组变量只包含对数组的引用,因此每次分配给它时,之前引用的数组都会被遗忘并丢弃。所以,不要预先初始化developerInfo。事实上,你甚至不需要在你使用它的地方声明它。

还有一种更简单的方法可以打印数组的内容:只需调用System.out.println(Arrays.toString(developerInfoR))。这样你甚至不需要打印代码中的内部循环。

您不需要任何变量 groupId、groupType、filePath、author、lineNo。只需写例如developerInfo[0] = parentElement.getAttributeValue("groupid"); 和类似的。这使得代码更明显。但是使用完整对象而不是 String[] 可能更有意义。有很多字段,每个字段的含义都在整数索引后面。

总而言之,考虑到这些建议以及一些额外的建议,您的代码可以重写为:

final String path = filePath.substring(1, filePath.lastIndexOf("."));
final Document doc = (Document) new SAXBuilder().build("A.xml");
final List<DeveloperInfo> developers = new ArrayList<String[]>();
for (Element parentElement : doc.getRootElement().getChildren())
  for (Element element : parentElement.getChildren())
    for (Element childElement : element.getChildren())
      developers.add(new DeveloperInfo(
          parentElement.getAttributeValue("groupid"),
          parentElement.getAttributeValue("type"),
          element.getAttributeValue("file"),
          path,
          childElement.getAttributeValue("author"),
          childElement.getAttributeValue("lineNo"),
      ));
for (DeveloperInfo d : developerTypes) System.out.println(d);

DeveloperInfo 类:

class DeveloperInfo {
  public final String groupId, groupType, filePath, author, lineNo;
  public DeveloperInfo(
      String groupId, String groupType, String filePath, 
      String author, String lineNo)
  {
    this.groupId = groupId; this.groupType = groupType; this.filePath = filePath;
    this.author = author; this.lineNo = lineNo;
  }
  public String toString() {
    return "DeveloperInfo [groupId=" + groupId + ", groupType=" + groupType + 
      ", filePath=" + filePath + ", author=" + author + ", lineNo=" + lineNo + "]";
  }

【讨论】:

    【解决方案3】:

    每次将其添加到 ArrayList 时,您都会引用同一个数组。

    而不是声明这个String[] developerInfo = {null, null, null, null, null};

    在开头。每次循环创建一个新数组。

    String[] developerInfo = new String[5];

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      • 2016-08-02
      • 2011-06-07
      • 1970-01-01
      • 2017-11-29
      相关资源
      最近更新 更多