2014-11-28 2 views
0

Я создал интерфейс, используя массивы для создания индекса цитирования. Я новый программист и хочу узнать, как преобразовать текущую реализацию Array в реализацию ArrayList. Вот мой код до сих пор. Как использовать ArrayLists в методе 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!"); 
    } 
} 

} 
+0

Похоже, что это просто вопрос о замене '' .length' с .size() 'и' [я] '' с .get (I) ', если я правильно понимаю ваш вопрос :) – xpa1492

ответ

1

Лучше всего использовать расширение для цикла для этого (он также работает для массивов, поэтому синтаксис был бы такой же с массивами и списками, если вы нашли его раньше)

 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()); 
       } 
      } 
     } 
1
for(Citation c:citationIndex){ 
    if(c!=null){ 
    //...code here 
    } 
} 

for (int i = 0; i < citationIndex.size(); i++) { 
    if (citationIndex.get(i) != null) { 
     //...code here 
    } 
}