日期:2014-05-20 浏览次数:20950 次
import java.io.*; import java.util.*; class MM<T> { private T name; public MM(T name) { setName(name); } public void setName(T name) { this.name=name; } public T getName() { return this.name; } public String toString() { return "The MM's name is "+this.name.toString(); } } public class GenericsDemo30 { public static final int quantities=5; public static void main(String[] args) throws IOException { Collection co1=new ArrayList(); String name=""; BufferedReader br=null; //创建 for(int i=0;i<quantities;i++) { br=new BufferedReader(new InputStreamReader(System.in)); name=br.readLine(); MM mm=new MM(name); co1.add(mm); } //输出 Iterator iter=co1.iterator(); while(iter.hasNext()) { System.out.println(iter.next()); } //删除 iter=co1.iterator(); System.out.println("输入想要移除的名字:"); br=new BufferedReader(new InputStreamReader(System.in)); name=br.readLine(); MM tmp=new MM(name); while(iter.hasNext()) { if(iter.next().getName()==tmp.getName())//The method getName() is undefined for the type Object... 提示Object里面没有这个方法,但删除元素不知道该怎么操作,求前辈们指点 { System.out.println("找到该mm"); iter.remove(); iter=co1.iterator(); } else { System.out.println("找不到该mm,删除失败"); iter=co1.iterator(); break; } } //输出 while(iter.hasNext()) { System.out.println(iter.next()); } iter=co1.iterator(); } }
public class IteratorRemovalDemo { private static final Scanner SCANNER = new Scanner(System.in); // 程序入口 public static void main(String[] args) { List<String> girls = inputGirls(); String girlName = prompt("Girl's name to be removed:"); removeGirlByName(girls, girlName); } /** * 用户输入 MM 名字 * * @return MM 名字列表 */ private static List<String> inputGirls() { List<String> girls = new ArrayList<String>(); String name; do { name = prompt("Enter a girl's name(press enter to finish):"); if (!name.equals("")) { girls.add(name); } } while (!name.equals("")); return girls; } /** * 提示用户输入 * * @param message 提示信息 * * @return 用户输入 */ private static String prompt(String message) { System.out.print(message); return SCANNER.nextLine().trim(); } /** * 从 MM 列表中删除指定的名字 * * @param girls MM列表 * @param girlName 要删除的名字 */ private static void removeGirlByName(List<String> girls, String girlName) { Iterator<String> girlsIterator = girls.iterator(); while (girlsIterator.hasNext()) { String name = girlsIterator.next(); if (name.equals(girlName)) { girlsIterator.remove(); System.out.println("\"" + girlName + "\" has been removed."); } } } }