Algorithm-VSM

 view release on metacpan or  search on metacpan

examples/corpus/LinkedListGeneric.java  view on Meta::CPAN

        T item;
        Node next = null;
        Node( T item ) { this.item = item; }
    }
    protected Node head = null, tail = null;
    public LinkedList() {}
    public void add( T item ) {
        if ( head == null ) { 
            head = new Node( item ); 
            tail = head; 
        }
        else { 
            tail.next = new Node( item ); 
            tail = tail.next; 
        }
    }
    public Iterator<T> iterator() {                               //(F)
        return new Iterator<T>() {                                //(G)
                protected Node ptr = head;

                public boolean hasNext() { return ptr != null; }

                public T next() {
                    if ( ptr != null ) {
                        T item = ptr.item; 
                        ptr = ptr.next; 
                        return item;
                    } else throw new NoSuchElementException();
                }
            };
    }
}

class Test {
    public static void main( String[] args ) {

        String str = "";

        //int list
        LinkedList<Integer> intList = new LinkedList<Integer>();
        intList.add( new Integer( 0 ) ); 
        intList.add( new Integer( 1 ) );
        intList.add( new Integer( 2 ) );
        Iterator<Integer> int_it = intList.iterator();
        while ( int_it.hasNext() )
            str += int_it.next().intValue() + "  ";               //(H)
        System.out.println( str );             //  0  1  2

        //string list 
        LinkedList<String> stringList = new LinkedList<String>();      
        stringList.add( "zero" ); 
        stringList.add( "one" );
        stringList.add( "two" );
        str = "";
        Iterator<String> string_it = stringList.iterator();
        while ( string_it.hasNext() )
            str += string_it.next() + "  ";                       //(I)
        System.out.println( str );             // zero  one  two

        // string list treated as int list
        // gives rise to compile-time error
        // Integer w = stringList.iterator().next();              //(J)
    }
}



( run in 0.818 second using v1.01-cache-2.11-cpan-140bd7fdf52 )