Ex.65 
import java.util.*;
public class WrappedString {
    private String s;
    public WrappedString(String s ) {
        this.s = s;
    }
    public static void main(String args[]){
        HashSet<Object> hs = new HashSet<Object>();
        WrappedString ws1 = new WrappedString("aardvark");
        WrappedString ws2 = new WrappedString("aardvark");
        String s1 = new String("aardvark");
        String s2 = new String("aardvark");
        
        hs.add(ws1);
        hs.add(ws2);
        hs.add(s1);
        hs.add(s2);
        System.out.print(hs.size());
        
    }
}
---------------------------------
output is 3 
---------------------------------
import java.util.*;
public class WrappedString {
    private String s;
    public WrappedString(String s ) {
        this.s = s;
    }
    public static void main(String args[]){
        HashSet<Object> hs = new HashSet<Object>();
        WrappedString ws1 = new WrappedString("aardvark");
        WrappedString ws2 = new WrappedString("aardvark");
        String s1 = new String("aardvark");
        String s2 = new String("aardvark");
        
        hs.add(ws1);
        hs.add(ws2);
        hs.add(s1);
        hs.add(s2);
        System.out.print(hs.size());
        
    }
    
    public boolean equals(Object o){
        if(this.s.equals(((WrappedString)o).s))
            return true;
        else
            return false;
    }
    
    public int hashCode(){
        return this.s.hashCode();
    }
}
---------------------------------
output is 2 
---------------------------------
沒有留言:
張貼留言