java - 将数组转换为ArrayList

标签 java arrays arraylist

我通过使用数组来创建引文索引来实现一个接口(interface)。我是一名新程序员,想学习如何将当前的 Array 实现转换为 ArrayList 实现。到目前为止,这是我的代码。如何在 printCitationIndex() 方法中使用 ArrayList 而不是数组?

    import java.util.ArrayList;

    public class IndexArrayList implements IndexInterface{
      ArrayList<Citation> citationIndex = new ArrayList<Citation>();
      private String formatType;
      private int totalNumCitations, numKeywords;
      ArrayList<Keyword> keywordIndex = new ArrayList<Keyword>();


    public void printCitationIndex(){
    // Pre-condition - the index is not empty and has a format type
    //Prints out all the citations in the index formatted according to its format type.  
   //Italicization not required
      if (!this.formatType.equals("")) {
        if (!isEmpty()) {
            for (int i = 0; i < citationIndex.length; i++) {
                if (citationIndex[i] != null) {
                    if (this.formatType.equals("IEEE")) {
                        System.out.println(citationIndex[i].formatIEEE());
                    } else if (this.formatType.equals("APA")) {
                        System.out.println(citationIndex[i].formatAPA());
                    } else if (this.formatType.equals("ACM")) {
                        System.out.println(citationIndex[i].getAuthorsACM());
                    }
                }
            }
        } else {
            System.out.println("The index is empty!");
        }
    } else {
        System.out.println("The index has no format type!");
    }
}

}

最佳答案

为此最好使用增强型 for 循环(它也适用于数组,因此如果您之前发现过的话,数组和列表的语法将是相同的)

        for (Citation citation : citationIndex) {
            if (citation != null) {
                if (this.formatType.equals("IEEE")) {
                    System.out.println(citation.formatIEEE());
                } else if (this.formatType.equals("APA")) {
                    System.out.println(citation.formatAPA());
                } else if (this.formatType.equals("ACM")) {
                    System.out.println(citation.getAuthorsACM());
                }
            }
        }

关于java - 将数组转换为ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27181332/

相关文章:

java - 添加到 ArrayList 时出错 - Java

java - 在 SwingUtilities.invokeLater 中放置(和不放置)什么?

java - 如何在 Gradle 多项目构建中配置每个 Kotlin 项目?

java - 扩展 Abstract Visualizer 时遇到困难 : getting ClassCastException

java - Jsp - 获取所有以字符开头的参数

c - 过滤 "Smoothing"C 中的数字数组

java - ArrayList trimtosize 不工作 android

Java 列表 : Difference between assignment while instantiating and after

C++:指针指向的值发生变化

使用大量元素和数组将 Javascript 重写为 DRY