Error retrieving a String after storing it as Object

0

I have this part of code:

System.out.print("nombre: ");
String nombre = leer.nextLine();

while(!nombre.equals("fin")){
    mc.insertar(mc, 0);
    System.out.print("nombre: ");
    nombre = leer.nextLine();
}
for (int i = 0; i < mc.cantidad();i++) {
    String aux = (String) mc.obtener(i);
    System.out.println(aux + " - "+aux.length()+" caracteres");
}

By the time you get to this part (thanks to debug): String aux = (String) mc.obtener(i);

Send the following error message:

  

Exception in thread "main" java.lang.ClassCastException:   Collections.CColection can not be cast to java.lang.String at   Collections.CTest.main (CTest.java:27)

In the class CColeccion the method obtener() is like this:

public Object obtener(int i){
    return datos[i];
}

The type of data I am working with is this: private Object datos[] = null; (practice before moving to ArrayList , generic and dynamic).

How do I convert it to String so that it gives me the name?

    
asked by Jose Luis 29.04.2017 в 22:32
source

1 answer

2

Your error is in this line of code:

mc.insertar(mc, 0);

In it you are inserting in your instance of CColeccion (called mc ) a reference to itself ( mc ) instead of inserting the string obtained in the previous step.

The error you are receiving, which is an exception at runtime and not a compilation error, is because you are trying to recover a String from a reference to CColeccion , hence the exception "CColection can not be cast to String" ("A CColection can not be converted to String").

Changing the program to save the content of nombre ,% String , the code is:

System.out.print("nombre: ");
String nombre = leer.nextLine();

while(!nombre.equals("fin")){
    mc.insertar(nombre, 0);
    System.out.print("nombre: ");
    nombre = leer.nextLine();
}

for (int i = 0; i < mc.cantidad();i++) {
    String aux = (String) mc.obtener(i);
    System.out.println(aux + " - "+aux.length()+" caracteres");

}

Now recovery of String stored will be successful and without throwing the exception at run time.

    
answered by 29.04.2017 в 23:43