I am trying to print the String, below is the code:
Object[] objArr = data.get(key);
for (Object obj : objArr)
{
System.out.println(obj);
cell.setValue(obj);
}
but I get following output in the console:
[[Ljava.lang.String;#7defb4fb]
I have tried the following snippets:
System.out.println(Arrays.toString(objArr));
System.out.println(Arrays.asList((objArr)));
System.out.println(objArr[k]);
But all of these are giving similar strange output:
[[Ljava.lang.String;#7defb4fb]
[[Ljava.lang.String;#7defb4fb]
[Ljava.lang.String;#7defb4fb
How do I get the string value out of it?
**
Edit:
**
My problem was to print and array of an array in Java. First thing was to recognize that its nested arrays and hence when I try to iterate over the array and print its elements it was printing the address of the address instead of the element.
[Ljava.lang.String;#7defb4fb]
My problem was to recognize this as an array and iterate over this array again in order to print the elements. Hence here was the solution
if (obj instanceof String[]) {
String[] strArray = (String[]) obj;
System.out.println(Arrays.toString(strArray));
// System.out.println(obj);
}
You can try instanceof and then cast it to String[].
Sample code:
String[] strArr = {"anc", "asda"};
Object[] objArr = {strArr, strArr}; // Array of String Arrays
for (Object obj : objArr) {
if (obj instanceof String[]) {
String[] strArray = (String[]) obj;
System.out.println(Arrays.toString(strArray));
// System.out.println(obj);
}
}
You need to iterate the array and print the strings one by one. If the individual objects are arrays, then you need to iterate them as well.
You need to iterate the array and print each element.if the array element is array you need to iterate throw them as well you can do that by reflection or use instanceof
ex :- if(obj instanceof int[]) or if(obj instanceof String[])
It will depend on what kind of data you are adding to array. Even if you iterate on array still printing object using SOP will call toString() method on the type class of the object.
So if you are adding objects of your own class then provide customized toString() method. And now iterate on array.
default implementation of object's toString() method will produce a string in following format getClass().getName() + '#' + Integer.toHexString(hashCode())
Best solution for your problem is use Arrays.deepToString(objArray) with custom toString() implementation if objArray contains objects of your defined class.
Look at the example below
public class ArrayPrint {
int age;
public static void main(String[] args) {
ArrayPrint obj1 = new ArrayPrint ();
obj1.age = 12;
ArrayPrint obj2 = new ArrayPrint ();
obj2.age = 15;
ArrayPrint[] ageArr = {obj1, obj2};
System.out.println(Arrays.deepToString(ageArr));
}
}
Output for this program shall be
[sfo.ArrayPrint#19f953d, sfo.ArrayPrint#1fee6fc]
But to get the actual content, if I override toString() method to my class like below
public String toString ()
{
return ""+age;
}
You get the output as below
[12,15]
So you see, Arrays.deepToString() shall be useful only if you have custom toString() implementation for your own class objects.
I had a similar problem. This is happening because Arrays.toString()is used on an array of objects which store separate elements and it fails when the array contains another array of objects within it, just like in your case. deepToString can be used to resolve this. I used Arrays.deepToString(Object[]) to convert the array of objects to string and then worked on the resultant string to find specific fields. Check out the second paragraph of the answer provided by #polygenelubricants in What is this: [Ljava.lang.Object;?
Check https://www.baeldung.com/java-tostring-array for more details on the solution.
Related
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;
}
}
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));
So, this is my dilemma. I have a class called:
public petShop()
and I used an ArrayList to collect all the strings (names of pets).
ArrayList<String> petNames = new ArrayList<>();
However, when using a different signature with an array in, the return type gives an error.
Any help?
public String[] getPetNames() {
return petNames;
You can get back an array from your ArrayList simply, using toArray.
public String [] getPetNameAsStringArray() {
return petNames.toArray(new String[petNames.size()]);
}
I'm having a config entry, from which I'm loading into an String array like
String s = "abc$#def$#ghi";
String[] scbHLNewArray = s.split("\\$\\#");
Here I'm comparing a string with the array values after splitting it like ,
for(String arrNewErrorInfo : scbHLNewArray) {
LOG.info("SCB HL New Error Value :"+arrNewErrorInfo+"\n");
if(errorInfo.equals(arrNewErrorInfo)) {
LOG.info("SCB HL Matched New value is :"+arrNewErrorInfo);
newState = ApplicationState.NEW;
addApplicationEvent(application.getId(),comment, ApplicationEventType.COMMENT,BBConstants.AUTOBOT);
scbHLNewStatus = "Matched";
break;
}
}
I want to use some util classes like List.. Any idea on append to list and compare the string with the list objecT?
Thanks,
Nizam
you can do this with List contains method.
ArrayList<Integer> arrlist = new ArrayList<Integer<(8);
// use add() method to add elements in the list
arrlist.add(20);
arrlist.add(25);
arrlist.add(10);
arrlist.add(15);
// list contains element 10
boolean retval = arrlist.contains(10); // It will return true.
Ok, let's try... First of all, you can create a List Object, wrapping your array very easily:
List<String> myList = Arrays.asList( scbHLNewArray );
Be carefull, because you can NOT add to this list, as it only wraps your array. If you want a list you can add to, you would have to create a new one, for example:
List<String> myModifiableList = new ArrayList<String>( myList );
This will create a new List that contains all the Strings from the first one but is also modifiable (you can add Strings, if you want).
In any case, you can use "contains", as Pratik has already shown, to test if a String is inside your list:
if (myList.contains("someString")) { ... }
This works because the String class already has well implemented equals(...) and hashCode() methods. If you want to put other Object than Strings into your list, you would have to make sure that these methods are implemented well, otherwise contains might not work as expected.
Yes you can use a list of course, you need to :
1. Take the result of split as an array.
2. Then convert this array to a list.
String s = "abc$#def$#ghi";
String[] scbHLNewArray = s.split("\\$\\#");
List<String> list=Arrays.asList(scbHLNewArray); //convert the array to a list
Take a look at Arrays.asList(Array a) and this Tutorial for further information about it.
And then to search the wanted String object you can use indexOf(Object o) or contains(Object o) List methods
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]);
}