简体   繁体   中英

Why is list.toArray() an object while converting ArrayList to String[]?

To make it very clear this is not a duplicate of these questions Convert ArrayList to String and Convert ArrayList containing strings but it is of relevance to them. Suppose we have a conversion method from ArrayList to String [] as described in answers of the first link I've referred to:

List<String> stockList = new ArrayList<String>();
stockList.add("stock1");
stockList.add("stock2");

String[] stockArr = new String[stockList.size()];
stockArr = stockList.toArray(stockArr);

for(String s : stockArr)
   System.out.println(s); 

With the print statement my output would look like this:

stock1
stock2

But what if I wanted my output to be in an array format (like [stock1,stock2] ) and I excluded the conversion to String , ie, the for loop towards the end.

If I would print out just the String[] it would give me a garbage value like [Ljava.lang.String;@5636bc0a . This I guess is probably because of problems with the jvm returns toArray as an object.

Why is it this way and what is the work around for this?

I need a String [] that gives me a meaningful value. I need it in this format because I am using this conversion to call a JAX-WS function in my project which accepts only String[] values:

myJaxWSObj.setValue(String[] myArrayOfStrings);

EDIT

Thanks for the answers, but some of you must have misunderstood the question. I want to convert ArrayList to String[] and not to String. So doing any sort of .toString() wouldn't help me much because as I mentioned above I need to call a JAX-WS class which accepts only String[] values. So the problem is not with System.out.println() .

Suppose I do a .toString() conversion I would need to convert it back to String[] by doing something like stockArr.split("") . I wanted to know if there is another work around for that.

EDIT 2

This has nothing to do with printing Arrays, it has to do with conversion of List to an Array of Strings.

Arrays are objects. Printing them using System.out.println() will call the default Object#toString() method which returns the object class name with a hashcode value. To print the string representation of an array, use Arrays.toString(Object[]) :

Returns a string representation of the contents of the specified array. If the array contains other arrays as elements, they are converted to strings by the Object.toString() method inherited from Object, which describes their identities rather than their contents.

There is a useful library function Arrays.toString(arr)

String[] arr = { "a", "b" };
System.out.println(Arrays.toString(arr));
//Output: [a, b]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM