Percorrendo uma Collection e pegando informações sobre seus elementos

1 resposta
M

Vou ser objetivo e preciso: eu tenho uma collection que guarda objetos nela. Cada um desses objetos tem o atributo String Label. Eu quero criar um método existsName(String name) que retorna true se o parâmetro name já for label de um objeto da Collection e retorna false senão.

Este método é de simples implementação, eu acho, estou me enrolando mesmo na hora de usar o Iterator. Um outro problema é que os objetos que a Collection guarda não são instâncias de Object, e sim de Objeto, que é uma classe do meu sistema.

Vlw !

1 Resposta

Mantu

Vou por um código passo a passo de uma solução trivial, ok?
Supondo que sua Collection esteja referenciada pela variável “coll”

public boolean existsName(String name) {
	Iterator it = coll.iterator();
	while(it.hasNext()){
		Object elem = it.next();
		if(elem instanceof JLabel) {
			JLabel lbl = (JLabel)elem;
			if(lbl.getText().equals(name))
				return true;
		}
	}
	return false;
}

(Editado…)
Uma solução um pouco mais sofisticada, seria vc criar uma TreeSet apartir dessa Collection e a partir de uma classe que implemente um Comparator:

public class Teste{
private Collection coll = Arrays.asList(
	new JLabel[] {new JLabel("Mantuaneli"), 
	new JLabel("Luciano")}
);

public boolean existsName(JLabel lbl) {
	TreeSet treeSet = new TreeSet(JLabelTextComparator.getInstance());
	treeSet.addAll(coll);
	return treeSet.contains(lbl);
}
public static class JLabelTextComparator implements Comparator{
	private static JLabelTextComparator instance = null;
	private JLabelTextComparator() {
	}
	public static JLabelTextComparator getInstance() {
		if(instance == null)
			instance = new JLabelTextComparator();
		return instance;
	}
	
	public int compare(Object o1, Object o2) {
		JLabel
			lbl1 = (JLabel)o1,
			lbl2 = (JLabel)o2
		;
		if(lbl1 == null || lbl2 == null)
			throw new ClassCastException();
		
		if(lbl1 == lbl2)
			return 0;
		
		String
			text1 = lbl1.getText(),
			text2 = lbl2.getText()
		;
		return text1.compareTo(text2);
	}
}
public static void main(String[] args) {
	Teste app = new Teste();
	JLabel 
		label1 = new JLabel("Antonio"),
		label2 = new JLabel("Luciano"),
		label3 = new JLabel("Mantuaneli"),
		label4 = new JLabel("Tertulino")
	;
	System.out.println("app.existsName(label1): " + app.existsName(label1));
	System.out.println("app.existsName(label2): " + app.existsName(label2));
	System.out.println("app.existsName(label3): " + app.existsName(label3));
	System.out.println("app.existsName(label4): " + app.existsName(label4));
}

}
Criado 2 de junho de 2006
Ultima resposta 2 de jun. de 2006
Respostas 1
Participantes 2