type casting with objects - java

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?

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.

since Paul has answered your main question ,let me answer your sub question
System.out.println(x.getClass().getName()); //how is this an
integer???
if you run the following simple code :
Object o = 45;
System.out.println(o.getClass().getName());
it will give you java.lang.Integer because the reference maybe of type Object but the actual value is a Integer.

Related

Why it's wrong when the variable of Object[] as elements of Object[] transfrom to Object[][]

I want to use object[] as the element of object[] to transform it to Object[][], but it can't run. So I want to know why it is wrong. And how can I achieve that giving a number k, and create a array that is k dimensional.
Here is the wrong code:
public static void main(String[] args) {
Object[] s = new Object[3];
s[0] = new Integer[1];
s[1] = new Integer[1];
s[2] = new Integer[1];
Object m = s;
Integer[][] t = (Integer[][])m;
System.out.println(Arrays.toString(t));
}
The type Object[][] is saying that the array can only contain other Object[] instances.
But an Object[] can also contain things that are not arrays of Object.
Note that when you cast from one reference type to another, no value conversion occurs, and the actual type of the object doesn't change. All that happens is that the runtime system checks that the object's actual runtime type is assignment compatible with the type you are casting to.
To illustrate why it has to be like this, consider the following:
Object[] s = new Object[2];
s[0] = new Integer[1];
Integer[][] t = (Integer[][]) s; // ONE
s[1] = "Hello";
Integer[] u = t[1]; // TWO
If (hypothetically!) the cast at "ONE" is allowed to succeed, then at "TWO" we would assign a String to a variable of type Integer[].
That cannot be allowed to happen. The cast must fail.
The second part of your question is this:
And how can I achieve that giving a number k, and create a array that is k dimensional.
It depends on what you mean:
You can create a custom class that behaves like a K-dimensional array, though you won't be able use Java array syntax to access and update cells.
You can construct a K-dimensional array out of Object[] objects, though you will need to do a lot of type-casting to use it. And under no circumstances will you be able to cast it to an array with a higher number of dimensions.
You can use java.lang.reflect.Array.newInstance(Class, int...) to create an array with K dimensions. The only problem that the declared type is Object so you still need a type cast:
Integer[][][] array = Array.newInstance(Integer.class, 3, 3, 3);
However, if you want K to be a parameter, then
int[] dimensions = new int[K];
for (int i = 0; i < K; i++) {
dimensions[i] = 2;
}
Object array = Array.newInstance(Integer.class, dimensions);
The problem is that when K is a parameter, you cannot declare a variable whose Java type is a K-dimensional array of Integer. If you want to subscript the array using [], you will need to resort to something like this:
switch (K) {
case 1:
Integer[] oneD = (Integer[]) array;
oneD[1] = 42;
break;
case 2:
Integer[][] twoD = (Integer[][]) array;
twoD[1][1] = 42;
break;
// etcetera
}
To answer the part
And how can I achieve that
You can do the below transform
Integer[][] t = Arrays.stream((Object[])m).map(Integer[].class::cast).toArray(Integer[][]::new);

How to compare an object containing a string?

I have an array that contains the following strings
Object[] array = {"Tom","Jim","George"};
How can I compare each object as a String?
* Array must be type of Object and contain only String type of objects for my problem.Using String[] is pretty much obvious enough.
Like that:
String testString = "xyz";
int result = testString.compareTo((String)array[i]);
or for example:
int result = ((String)array[j]).compareTo((String)array[i]);
If you are not really sure if the array element is a String, use the instanceof operator to check.
Try this
int result=-1;
Object parameter="Tom";
for(Object o: array){
if(o.toString().equals(parameter.toString())){
result=1;
}
}

How to add to an array in java, and then print out using for loop? [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 6 years ago.
So in the beginning, I just had this code to add to my array:
public void getMyArray()
{
myArray[0] = ("String1");
myArray[1] = ("String2");
}
But I kept getting a null pointer exception whenever I called it, and I wasn't sure why. So I changed my code to this:
public void getMyArray()
{
String [] myArray = {"String1", "String2"};
System.out.println(myArray);
}
And now I get what seems to be the address when printing:
[Ljava.lang.String;#1ca6218
You can use Arrays.toString() like this:
System.out.println(Arrays.toString(myArray));
Replacing it in your code:
public void getMyArray()
{
String [] myArray = {"String1", "String2"};
System.out.println(Arrays.toString(myArray));
}
The output will be:
[String1, String2]
The toString() method for an array will not print out all objects in an array in java, unless you want to override it and make your own implementation. What is printing is a description of the array object.
To print all elements in the array you would do something like:
for(String myArray1 : myArray) {
System.out.println(myArray1);
}
Also, the size of an array in java is fixed at instantiation. Whatever amount of memory you allocate for the array is there to stay. If you want to change the size, look into ArrayLists or LinkedLists and other structures. Hope this helps.
i imagine that you are not initializing youre array anywhere, using something like
myArray = new String[2];
But, besides that, the second option you have there is printing that because its actually printing the objects string encoding for a String array. instead, you will have to loop through each element and print it inidividually
for(int i = 0; i < myArray.length; i++)
{
System.out.println(myArray[i]);
}
The reason you get [Ljava.lang.String;#1ca6218 on output is because an object's default string representation is its bytecode representation in the JVM.
Since there is no way in the Java language to override array's toString(), you can create a utility method to make a more appropriate string.
Here is an example for you:
public static String arrayToString(String[] array) {
StringBuilder builder = new StringBuilder();
for (String s : array) builder.append(s).append(" ");
String result = builder.toString();
return result.substring(0, result.length() - 1);
}
You can also use Java's built-in array to string via the Arrays utility class:
Arrays.toString(myArray)
The reason you get a null pointer or index out of bounds is because your array variable reference is either null or not to an appropriately sized array.
In your problem, you will need an array of 2 elements, thus new String[2]
You can then use normal assignment and it should work, along with the above method to print out the string.
String[] myArray = new String[2];
myArray[0] = "Hello";
myArray[1] = "there.";
System.out.println(Arrays.toString(myArray));
Use java.util.Arrays#toString
System.out.println(Arrays.toString(myArray));

How to get the sum of an LinkedList (Sum up items in a LinkedList)

What I'm trying to do is get the sum of all integer items retrieved from the database then added into a LinkedList, like so:
ManageFeeNotePOJO selectedRecord = (ManageFeeNotePOJO) manageFeeNoteListTableView().getItems().get(selectdIndex);
List toFeeBillListTot = new LinkedList();
toFeeBillListTot.add(selectedRecord.getFeeNoteValue());
int sum = 0;
for (Object sumItem : toFeeBillListTot) {
sum += sumItem;
}
System.out.println(sum);
With this I get the error:
bad operand types for binary operator '+'
first type: int
second type: Object
The other approach is:
ManageFeeNotePOJO selectedRecord = (ManageFeeNotePOJO) manageFeeNoteListTableView().getItems().get(selectdIndex);
List toFeeBillListTot = new LinkedList();
toFeeBillListTot.add(selectedRecord.getFeeNoteValue());
int sum = 0;
for (int i = 0; i < toFeeBillListTot.size(); i++) {
sum += (int) toFeeBillListTot.get(i);
}
System.out.println(sum);
I get java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer error with this
Please, I would be more than greatful for any working approach around this. Thank you in advance.
bad operand types for binary operator '+'
first type: int
second type: Object
This is saying: "You can't use the + operator with one these two types" - and I bet you can guess which one - Object - which, if you think about it, makes sense:
Remember that every class of every type you'll ever work with in Java extends Object. So, when you're working with something that has been cast to Object, Java knows almost nothing about what that something is. In particular, it would have no freaking clue what to do with a + applied to one.
For instance, imagine that you had a Person class and did
Person a = new Person();
Person b = new Person();
a + b; //WTF??
Would that make sense? Of course not.
Now, you might say "but I didn't add Objects to my list, I added Integers/Doubles/some other type that the + operator should work with" - and I'm sure you would be right, but the problem is that you added them to a List of Objects, which you created as such right here:
List sum toFeeBillListTot = new LinkedList();
When you do this, you're creating an "untyped list". This means you can add objects of any type you like to it - which might sound nice, but as a natural consequence, you can only retrieve Objects from it, which is what you're doing now.
By "use a generic collection", #Jeroen is suggesting you do this instead:
List<Integer> toFeeBillListTot = new LinkedList<>();
Rather than creating a list of Objects, the <Integer> means you're creating a list of integers, which means you can only add Integers to it, and also that every element you pull out of it will be an Integer, so you can do:
int sum = 0;
for (Integer sumItem : toFeeBillListTot) {
sum += sumItem;
}
First, I feel a bit weird about the use of raw types with your List declaration. By that, I mean you do not provide the type argument to it.
If you've got an expectation that you're getting back a list of Strings, then you should declare it as such:
List<String> toFeeBillListTot = new LinkedList<>();
Next, you can't simply add up Strings, as that has no meaning. You have to convert them all to some numerical type, probably Double:
double sum = 0;
for(String bill : toFeeBillListTot) {
sum += Double.parseDouble(bill);
}
Not that the above conversion will only work if there aren't any other unusual characters in your conversion (that is, no thousands separators).

How to convert object array to string array in Java

I use the following code to convert an Object array to a String array :
Object Object_Array[]=new Object[100];
// ... get values in the Object_Array
String String_Array[]=new String[Object_Array.length];
for (int i=0;i<String_Array.length;i++) String_Array[i]=Object_Array[i].toString();
But I wonder if there is another way to do this, something like :
String_Array=(String[])Object_Array;
But this would cause a runtime error: Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
What's the correct way to do it ?
Another alternative to System.arraycopy:
String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);
In Java 8:
String[] strings = Arrays.stream(objects).toArray(String[]::new);
To convert an array of other types:
String[] strings = Arrays.stream(obj).map(Object::toString).
toArray(String[]::new);
System.arraycopy is probably the most efficient way, but for aesthetics, I'd prefer:
Arrays.asList(Object_Array).toArray(new String[Object_Array.length]);
I see that some solutions have been provided but not any causes so I will explain this in detail as I believe it is as important to know what were you doing wrong that just to get "something" that works from the given replies.
First, let's see what Oracle has to say
* <p>The returned array will be "safe" in that no references to it are
* maintained by this list. (In other words, this method must
* allocate a new array even if this list is backed by an array).
* The caller is thus free to modify the returned array.
It may not look important but as you'll see it is... So what does the following line fail? All object in the list are String but it does not convert them, why?
List<String> tList = new ArrayList<String>();
tList.add("4");
tList.add("5");
String tArray[] = (String[]) tList.toArray();
Probably, many of you would think that this code is doing the same, but it does not.
Object tSObjectArray[] = new String[2];
String tStringArray[] = (String[]) tSObjectArray;
When in reality the written code is doing something like this. The javadoc is saying it! It will instatiate a new array, what it will be of Objects!!!
Object tSObjectArray[] = new Object[2];
String tStringArray[] = (String[]) tSObjectArray;
So tList.toArray is instantiating a Objects and not Strings...
Therefore, the natural solution that has not been mentioning in this thread, but it is what Oracle recommends is the following
String tArray[] = tList.toArray(new String[0]);
Hope it is clear enough.
The google collections framework offers quote a good transform method,so you can transform your Objects into Strings. The only downside is that it has to be from Iterable to Iterable but this is the way I would do it:
Iterable<Object> objects = ....... //Your chosen iterable here
Iterable<String> strings = com.google.common.collect.Iterables.transform(objects, new Function<Object, String>(){
String apply(Object from){
return from.toString();
}
});
This take you away from using arrays,but I think this would be my prefered way.
This one is nice, but doesn't work as mmyers noticed, because of the square brackets:
Arrays.toString(objectArray).split(",")
This one is ugly but works:
Arrays.toString(objectArray).replaceFirst("^\\[", "").replaceFirst("\\]$", "").split(",")
If you use this code you must be sure that the strings returned by your objects' toString() don't contain commas.
If you want to get a String representation of the objects in your array, then yes, there is no other way to do it.
If you know your Object array contains Strings only, you may also do (instread of calling toString()):
for (int i=0;i<String_Array.length;i++) String_Array[i]= (String) Object_Array[i];
The only case when you could use the cast to String[] of the Object_Array would be if the array it references would actually be defined as String[] , e.g. this would work:
Object[] o = new String[10];
String[] s = (String[]) o;
You can use type-converter.
To convert an array of any types to array of strings you can register your own converter:
TypeConverter.registerConverter(Object[].class, String[].class, new Converter<Object[], String[]>() {
#Override
public String[] convert(Object[] source) {
String[] strings = new String[source.length];
for(int i = 0; i < source.length ; i++) {
strings[i] = source[i].toString();
}
return strings;
}
});
and use it
Object[] objects = new Object[] {1, 23.43, true, "text", 'c'};
String[] strings = TypeConverter.convert(objects, String[].class);
For your idea, actually you are approaching the success, but if you do like this should be fine:
for (int i=0;i<String_Array.length;i++) String_Array[i]=(String)Object_Array[i];
BTW, using the Arrays utility method is quite good and make the code elegant.
Object arr3[]=list1.toArray();
String common[]=new String[arr3.length];
for (int i=0;i<arr3.length;i++)
{
common[i]=(String)arr3[i];
}
Easily change without any headche
Convert any object array to string array
Object drivex[] = {1,2};
for(int i=0; i<drive.length ; i++)
{
Str[i]= drivex[i].toString();
System.out.println(Str[i]);
}

Categories