Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type casting with objects

Tags:

java

casting

I am trying to convert two objects to integers, add them, and then convert them back to objects and store them in an Object array. I when I try adding the Objects back into the array, though, I get an Array Store Exception.

Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
str = str.replaceAll("[^0-9]+", " "); 
Object[] numbersArray = Arrays.asList(str.trim().split(" ")).toArray();
str = scanner.nextLine();
str = str.replaceAll("[^0-9]+", " "); 
Object[] translateArray = Arrays.asList(str.trim().split(" ")).toArray();

for (int i = 0; i < numbersArray.length; i+=2) {
     Object x = (Object) (Integer.parseInt(numbersArray[i].toString()) 
                   + Integer.parseInt(translateArray[0].toString()));
     Object y = (Object) (Integer.parseInt(numbersArray[(i+1)].toString()) 
                   + Integer.parseInt(translateArray[1].toString()));

     System.out.println(x.getClass().getName()); //how is this an integer???
     System.out.println(y); //values get added correctly...
     numbersArray[i] = (Object) x;
     numbersArray[i+1] = (Object) y;
  }

As you can probably see, I am trying to cast the Object type everywhere I can, but numbersArray refuses to take it. I think my problem has something to do with the assignment statements of Objects x and y. Why are they still coming up as integers?

like image 872
Steve C Avatar asked Sep 16 '26 09:09

Steve C


1 Answers

numbersArray is really a String[]. This is because String.split() returns a String[] and Arrays.asList(array).toArray() works by simply calling clone() on the wrapped array.

As a result, when you try to store an Integer in the String[] you get an ArrayStoreException.

If you want to get a true Object[] you can do

List<String> list = Arrays.asList(str.trim().split(" "));
Object[] numbersArray = list.toArray(new Object[list.size()]);

However, I would consider changing your design. Using an Object[] first to store Strings and then Integers is likely to cause confusion and bugs.

like image 180
Paul Boddington Avatar answered Sep 17 '26 22:09

Paul Boddington