package arraylist; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; public class FamousQuotes { private static ArrayList listOfFamousQuotes; private static ArrayList<String> listOfFamousQuotesTypechecked; public static void main(String[] args) { FamousQuotes app = new FamousQuotes(); System.out.println("没有引用泛型添加三个人说的三句名言"); app.bulidList(); app.printList(); System.out.println("======================="); System.out.println("引用泛型添加三个人说的三句名言"); app.bulidCheckedList(); app.printCheckedList(); System.out.println("========================"); System.out.println("没有泛型版本的删除方式指定人说的名言"); String strAuthor = "Winston Churchill"; System.out.println("删除这个人说的名言后再输出看看还有没有这个人说的话 "+strAuthor); app.expurgate(listOfFamousQuotes, strAuthor); app.printList(); System.out.println("有泛型版本的删除方式指定人说的名言"); System.out.println("删除这个人说的名言后再输出看看还有没有这个人说的话 "+strAuthor); app.expurgateCheckedList(listOfFamousQuotesTypechecked, strAuthor); app.printCheckedList(); } //没有泛型添加三个人说的三句名言 void bulidList() { listOfFamousQuotes = new ArrayList(); listOfFamousQuotes.add("Where there is love there is life - Mahatma Gandhi"); listOfFamousQuotes.add("A joke is a very serious thing - Winston Churchill"); listOfFamousQuotes.add("In the end,everything is a gag -Charlie Chaplin"); } //有泛型添加三个人说的三句名言 void bulidCheckedList() { listOfFamousQuotesTypechecked = new ArrayList<String>(); listOfFamousQuotesTypechecked.add("Where there is love there is life - Mahatma Gandhi"); listOfFamousQuotesTypechecked.add("A joke is a very serious thing - Winston Churchill"); listOfFamousQuotesTypechecked.add("In the end,everything is a gag -Charlie Chaplin"); } //没有泛型输出三个人说的三句名言 void printList() { Iterator listIterator = listOfFamousQuotes.iterator(); while(listIterator.hasNext()) { String quote = (String)listIterator.next(); System.out.println(quote); } } //有泛型输出三个人说的三句名言 void printCheckedList() { Iterator<String> quoteIterator = listOfFamousQuotesTypechecked.iterator(); while(quoteIterator.hasNext()) { String quote = quoteIterator.next(); System.out.println(quote); } } //没泛型删除 void expurgate(Collection c,String strAuthor) { for(Iterator i=c.iterator();i.hasNext();) { if(((String)i.next()).contains(strAuthor)) { i.remove(); } } } //有泛型的删除 void expurgateCheckedList(Collection<String> c,String strAuthor) { for(Iterator<String> i = c.iterator();i.hasNext();) { if(i.next().contains(strAuthor)) { i.remove(); } } } }
时间: 2024-10-07 11:34:25