天天看點

測試Set的列印輸出

//PrintSet.java

package com.msn.spaces.bryantd001;

import java.util.*;

class MyHashSet extends HashSet{

      public String toString(){

            String result = "{";

            Iterator it = iterator();

            while (it.hasNext()){

                  result += it.next().toString() + ' ';

            }

            result += "}";

            return result;

      }

}

class  MyTreeSet extends TreeSet{

      public String toString(){

            String result = "{";

            Iterator it = iterator();

            while (it.hasNext()){

                  result += it.next().toString() + ' ';

            }

            result += "}";

            return result;

      }

}

class MyLinkedHashSet extends LinkedHashSet{

      public String toString(){

            String result = "{";

            Iterator it = iterator();

            while (it.hasNext()){

                  result += it.next().toString() + ' ';

            }

            result += "}";

            return result;

      }

}

public class PrintSet{

      static void fill(Set set){

            for (int i = 0; i < 5; i++){

                  set.add(new Integer(i));

            }

      }

      public static void main(String[] args){

            HashSet hs = new HashSet();

            TreeSet ts = new TreeSet();

            LinkedHashSet lhs = new LinkedHashSet();

            fill(hs);

            fill(ts);

            fill(lhs);

            System.out.println("Show the order of the Sets by the default toStrintg() way.");

            System.out.println(hs);

            System.out.println(ts);

            System.out.println(lhs);

            System.out.println();

           MyHashSet mhs = new MyHashSet();

           MyTreeSet mts = new MyTreeSet();

           MyLinkedHashSet mlhs = new MyLinkedHashSet();

           fill(mhs);

           fill(mts);

           fill(mlhs);

           System.out.println("Show the order of the Customized Sets by my toString() way.");

           System.out.println(mhs);

           System.out.println(mts);

           System.out.println(mlhs);  

     }

}