/* * @topic T01355 List, Iterator, Generic Box Container * @brief Main driver */ package week11demo; import java.util.Iterator; import java.util.LinkedList; public class MainApp { private static void display( List< String > strings ) { for ( String str : strings ) { System.out.print( str + ", " ); } System.out.println(); }//display private static void removeHello( List< String > strings ) { /* Incorrect implementation for( int idx = 0; idx < strings.size(); ++idx ) { //if ( strings.get( idx ).equals( "Hello" ) ) { if ( "Hello".equals( strings.get( idx ) ) ) { // remove it! strings.remove(idx); } } */ // Correct implementation Iterator<String> it = strings.iterator(); while ( it.hasNext() ) { if ((it.next().equals("Hello"))) { it.remove(); } } }//removeHello public static void main(String[] args) { // List demo List< String > strings = new LinkedList< String >(); strings.add("Hello"); strings.add("Hello"); strings.add("Hello"); strings.add("Hello"); strings.add(0, "World"); strings.add("!"); strings.add("Hello"); strings.add("again"); display( strings ); // How to remove all "Hello" elements removeHello( strings ); display( strings ); //Box demo Box<String> box = new Box<String>(); box.set( "hello" ); System.out.println( box.get() ); Box<Integer> ibox = new Box<>(); ibox.set( 123 ); System.out.println( ibox.get() ); }//main }//class MainApp