How to convert Object[] filled with tokens to an Integer Array? - java

I am trying to write a method that takes in an Object[] that is populated with tokens and converts it to an array of integers.
I started out with an ArrayList:
ArrayList<String> colArr = new ArrayList<String>();
then populated it with tokens from a .txt file:
while(st.hasMoreTokens()){
colArr.add(st.nextToken());
}
then converted it to an Object[]:
Object[] newColArr = colArr.toArray();
I now need to write a method that converts this Object[] to an Integer so that I can add certain elements together. This is what I tried:
public static Integer[] convert(Object[] objectArray){
Integer[] intArray = new Integer[objectArray.length];
for(int i=0; i<objectArray.length; i++){
intArray[i] = (Integer) objectArray[i];
}
return intArray;
}
but got "Error: java.lang.String cannot be cast to java.lang.Integer".

use Integer.valueOf(objectArray[i]) instead of casting like (Integer)objectArray[i]
EDIT:
To clarify, remember that Integer.valueOf() is simply a boxed object around Integer.parseInt().. so you have to handle NumberFormatException.
If you are quite sure that your text file will only contain integers, you could simply have an arraylist of integers and do the Integer.valueOf(tokenizer.nextToken())

Integer.parseInt( string ); works for getting an Integer from String

loop through your array of strings and use Integer.parseInt();

You can't typecast directly from a java.lang.String to a java.lang.Integer, they are two totally different objects. Instead try doing:
Integer.parseInt(objectArray[i])
Don't forget to handle java.lang.NumberFormatException. And one more thing, you don't need to do the intermediary conversion to Object array. Unless of course your using that for something else you didn't mention. Cheers.

if you know, that the object array contains strings, you can use Integer.parseInt() to convert the String to a Integer

You can also use guava's Lists.transform.
List<String> numberList=Lists.newArrayList("1","2","3");
List<Integer> trnsList = Lists.transform(numberList,new Function<String,Integer>() {
#Override
public Integer apply(String arg0) {
return Integer.valueOf(arg0);
}
});
Integer[] intArr=trnsList.toArray(new Integer[trnsList.size()]);

Related

Converting a List to an Array in Java

I am a List of Long type and would like to convert it to an array of long type.
However when adding elements to the list, it says it is unable to find method "add(int)"
my code looks like below
package collections;
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public class ListToArray {
private static List<Long> list;
public static void main(String[] args){
list=new ArrayList<Long>();
list.add(121145788);
list.add(1245898);
long[] arr=new long[list.size()];
arr=list.toArray();
}
}
Error I am getting are
Error(16,13): cannot find method add(int).
Error(21,25): incompatible types
Can someone point out where it's going wrong.
As suggested in the comments, you should add L to force the value to be a long:
list.add(121145788L);
list.add(1245898L);
Explanation:
the values you wanted to add are ints, and list is for longs. Adding the L makes the compiler use the number literal as a value of type Long explicitly, and that can be added to the list.
Without it, the numbers are treated as Integers, and those can't be added to a list of type Long, hence
cannot find method add(int)
There is a method add(long), and that's what is used when the L is used.
To convert to an array, you need to do it the old fashioned way:
for (int i = 0; i < arr.length; i++) {
arr[i]=list.get(i);
}
This is because long is a primitive, and Long is a reference type (i.e. it is an Object). Casting from primitives to Objects isn't always easy. In this case, the old fashioned way works well.
First, this is your code but with all the fixes!
private static List<Long> list;
public static void main(String[] args){
list=new ArrayList<Long>();
list.add(121145788L);
list.add(1245898L);
Long[] arr = new Long[list.size()];
list.toArray(arr);
}
And here is some explanation:
you have a list of type Long. When you add() items to the list - compiler expects them to be of type Long, but you are adding literal values (plain numbers like 121145788) so those are treated as integers (type int) and are autoboxed to Integer instead of Long. So add L to treat literals as long and then they are autoboxed into Long. Fine for the compiler :)
list.toArray(arr); this is the correct method to kinda convert a list to an array. Because the method you used returns array of Object and arr you created is not an array of Object.
And again this correct method I used takes T[] as input, so you need to change your arr declaration a bit to make it of type Long instead of an array of primitive type long.
If for some reason you need long[], the easiest way would be:
long[] arr = new long[list.size()];
for (int i=0; i < list.size(); i++) {
arr[i] = list.get(i);
}
Error(16,13): cannot find method add(int), this is because you are passing int instead of a Long value in a list of Long. You should be doing:
list.add(121145788l);
And for the second error follow this.Hope,it helps!
JVM doesn't automatically cast int (short, byte, char) to Long. It's explained on the next link.
Java: Why can't I cast int to Long
Converting List<Long> to long[] is possible and also is answered on SO.
How to convert List<Integer> to int[] in Java?
That's the answers:
using Java 8 streams
long[] arr = list.stream().mapToLong(Long::longValue).toArray();
using Guava
long[] arr = Longs.toArray(list);
using Apache Commons Lang
long[] arr = ArrayUtils.toPrimitive(list.toArray(new Long[0]))

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));

Java convert from String array to short array?

hello I have a commaseparated list of string and put into an array.
I ultimately need them as a list of shorts, but the only way I know how to do that is get them as an array of shorts then do array.asList()
String[] stringArray= commaSeparatedString.split("\\s*,\\s*");
How can I get that to an array of shorts so I can throw in a list?
THanks
Well presumably you just need to parse each element. But why not just add them to an ArrayList<Short>?
List<Short> shortList = new ArrayList<Short>(stringArray.length);
for (int i = 0; i < stringArray.length; i++) {
shortList.add(Short.valueOf(stringArray[i]));
}
(Note that you can't have a list of a primitive type, as Java generics don't support primitive type arguments.)
After the splitting you parse each string to the desired type for example Short.parseShort(element)

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