论坛首页 Java企业应用论坛

实现Set中不保存相同类的实例

浏览 1774 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-07-17   最后修改:2009-07-17
OO
public interface IA {
}


public class B implements IA {
}


public class C implements IA {
}


public class Main {
	
	Set<IA> classSet = new HashSet<IA>();
	
	public void setClassSet(Set<IA> set){
		this.classSet = set;
	}
	
	public boolean validation(IA a){
		boolean flag = true;
		Iterator<IA> it = classSet.iterator();
		while(it.hasNext()){
			String paramClass = a.getClass().getCanonicalName();
			String paramClassName = paramClass.substring(paramClass.lastIndexOf('.')+1);
			
			IA obj = it.next();
			String savedClass = obj.getClass().getCanonicalName();
			String savedClassName = savedClass.substring(savedClass.lastIndexOf('.') + 1);
			
			if ( paramClassName.equals(savedClassName)){
//				classSet.add(a);
				flag = false;
				System.out.println("you register class has registered : "+paramClassName);
			}
		}
		return flag;
		
	}

	public static void main(String[] args) throws ClassNotFoundException {
		B b = new B();
		C c = new C();
		Set<IA> set = new HashSet<IA>();
		set.add(b);
		Main m = new Main();
		m.setClassSet(set);
		
		if(m.validation(c)){
			set.add(c);
		}
		
		m.validation(b);
		
		System.out.println(set.size());
}
}
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics