1
Aprender a programar desde cero / Re:CU00678B java.lang.ClassCastException: java.lang.Integer cannot be cast String
« en: 29 de Marzo 2015, 18:37 »
Buenos días,
te comento que cambie las líneas que me indicaste especialmente la parte de no repetir el it.next(); sin embargo no entiendo ¿por qué no me corre como yo quisiera?
En mi primer if en la línea 21:
21 if(itStringInteger instanceof HashSet ){
obviamente no ingresa al if porque el objeto itStringInteger es del tipo <Set> entonces todos se van por el "else", pero si yo quisiera comprobar el tipo de objeto que estoy manejando ¿ Cómo hago para que este if funcione?
te comento que cambie las líneas que me indicaste especialmente la parte de no repetir el it.next(); sin embargo no entiendo ¿por qué no me corre como yo quisiera?
En mi primer if en la línea 21:
21 if(itStringInteger instanceof HashSet ){
obviamente no ingresa al if porque el objeto itStringInteger es del tipo <Set> entonces todos se van por el "else", pero si yo quisiera comprobar el tipo de objeto que estoy manejando ¿ Cómo hago para que este if funcione?
Código: [Seleccionar]
import java.util.*;
public class TestEjercicio78 {
public static void main (String [ ] Args) { //main cuerpo del programa ejemplo aprenderaprogramar.com
ArrayList<Set> arraySet = new ArrayList<Set>();
HashSet<String> arrayString = new HashSet<String>();
TreeSet<Integer> arrayInteger = new TreeSet<Integer>();
arrayString.add("sol");arrayString.add("luna");arrayString.add("saturno");
arrayInteger.add(2);arrayInteger.add(8);arrayInteger.add(5);
arraySet.add(arrayString);
arraySet.add(arrayInteger);
Iterator<Set> it = arraySet.iterator();
Set tmpAnalizando;
while ( it.hasNext() ) { //Utilizamos el método hasNext de los objetos tipo Iterator
Iterator itStringInteger = it.next().iterator();
if(itStringInteger instanceof HashSet ){
System.out.println("Nombre de clase detectado: HashSet");
//En caso de que sea objeto string
int contadorString = 0;
while ( itStringInteger.hasNext() ){
System.out.println("Objeto " + contadorString + " String detectado: " + itStringInteger.next());
contadorString++;
}
}else{
System.out.println("Nombre de clase detectado: TreeSet");
//En caso de que sea objeto string
int contadorInteger = 0;
while ( itStringInteger.hasNext() ){
System.out.println("Objeto " + contadorInteger + " String detectado: " + itStringInteger.next());
contadorInteger++;
}
}
} //Cierre del while
}
}