Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 3522

What is [Ljava.lang.Object;?

$
0
0

1. Overview

In this tutorial, we'll learn what [Ljava.lang.Object means and how to access the proper values of the object.

2. Java Object Class

In Java, if we want to print a value directly from an object, the first thing that we could try is to call its toString method:

Object[] arrayOfObjects = { "John", 2, true };
assertTrue(arrayOfObjects.toString().startsWith("[Ljava.lang.Object;"));

If we run the test, it will be successful, but usually, it's not a very useful result.

What we want to do is print the values inside the array. Instead, we have [Ljava.lang.Object. The name of the class, as implemented in Object.class:

getClass().getName() + '@' + Integer.toHexString(hashCode())

When we get the class name directly from the object, we are getting the internal names from the JVM with their types, that's why we have extra characters like [ and L, they represent the Array and the ClassName types, respectively.

3. Printing Meaningful Values

To be able to print the result correctly, we can use some classes from the java.util package.

3.1. Arrays

For example, we can use two of the methods in the Arrays class to deal with the conversion.

With one-dimensional arrays, we can use the toString method:

Object[] arrayOfObjects = { "John", 2, true };
assertEquals(Arrays.toString(arrayOfObjects), "[John, 2, true]");

For deeper arrays, we have the deepToString method:

Object[] innerArray = { "We", "Are", "Inside" };
Object[] arrayOfObjects = { "John", 2, innerArray };
assertEquals(Arrays.deepToString(arrayOfObjects), "[John, 2, [We, Are, Inside]]");

3.2. Streaming

One of the significant new features in JDK 8 is the introduction of Java streams, which contains classes for processing sequences of elements:

Object[] arrayOfObjects = { "John", 2, true };
List<String> listOfString = Stream.of(arrayOfObjects)
  .map(Object::toString)
  .collect(Collectors.toList());
assertEquals(listOfString.toString(), "[John, 2, true]");

First, we've created a stream using the helper method of. We've converted all the objects inside the array to a string using map, then we've inserted it to a list using collect to print the values.

4. Conclusion

In this tutorial, we've seen how we can print meaningful information from an array and avoid the default [Ljava.lang.Object;.

We can always find the source code for this article over on GitHub.


Viewing all articles
Browse latest Browse all 3522

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>