This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
I'm trying to convert a list of objects into json but the values are the location in memory.
public class User {
private String name;
private int score;
public User(String name, int score){
this.name = name;
this.score = score;
}
User user1= new User("Luke", 50);
User user2 = new User("Ryan", 70);
List<User> list = Arrays.asList(user1, user2);
Gson gson = new Gson();
String json = gson.toJson(list);
System.out.println(list);
The last line is supposed to show my objects in json but instead i just get [User#579bb367, User#1de0aca6], why is this? thanks
You meant
System.out.println(json);
What you did was to print the List, that, without a toString, will just print a default hash
You just print the hashcode of the list. When you call System.out.println() method, it will call toString() method of List. It is
getClass().getName() + '#' + Integer.toHexString(hashCode())
You need to implement a toString() method for the Object inside your list, or you will get the hash codes.
When you print a list, you're in fact (implicitly) calling its toString() method, which usually just calls each of its element's toString()s, concatinates them with commas and encloses them in brackets. If your User class does not override toString() it will use Object's implementation that just prints the class' simple name and its default hashCode(), which is typically the memory address. If you want something more intelligent there, you'd have to override toString(). E.g.:
#Override
public String toString() {
return String.format("[User name %s, score %d]", name, score);
}
Related
This question already has answers here:
How to use the toString method in Java?
(13 answers)
Closed 4 years ago.
I have 2 objects:
ObjectA
ObjectB
When I turn ObjectA to a string (ObjectA.toString()) it looks like this:
projectA.test.Object#e6db18d
Now with ObjectB when I turn it to a string (ObjectB.toString()) it looks like this:
ObjectB {color=StringProperty [value: blue], car=StringProperty [value: bmw]}
Now my question is why does one present a a string of numbers and letters while the other one presents me with a list? How can I do it that all my objects are presented like lists similar to ObjectB as this would be easier to read?
The string value of an object is obtained through the toString() method. Therefore, to change the string representation of an object, the toString() method must be overridden in the class:
public class SomeClass {
#Override
public String toString() {
return "Custom string";
}
}
The string representation of ObjectA is the default string representation of any object, where the name of the class of the object is printed, followed by #, and finally, the hash code of the object. The default implementation is:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
This question already has answers here:
When we override the toString() method we should always return a string representation of the object?
(6 answers)
Closed 4 years ago.
Should the method toString() in java ever return null if no conversion could be done or should it return an empty string in that case instead?
null is not String so it is not allowed to return here. Check Java Docs:
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
it should return a meaningful string representation of the object. I wrote an example of how to use it and why it is useful:
public class Car {
private String make;
private int year;
public Car(String make, int year) {
this.make = make;
this.year = year;
}
#Overrride
public String toString() {
return "Car Make:" + make + "; Built Year: " + year;
}
}
Example:
Car myCar = new Car("Nissan", 1999);
Car yourCar = new Car("BMW", 2018);
System.out.println(myCar); // call toString() implicitly
System.out.println(yourCar);
It will print 2 lines and you can easily read the text and know which is your car!
Car Make:Nissan; Built Year: 1999
Car Make:BMW; Built Year: 2018
toString() returning null would be very bad API design. Clearly, if you are able to call toString() on it, the object is clearly not null. Otherwise, there would be a NullPointerException.
It really depends on the Object and what the use case is. Empty string is ok if you are using toString() to do real logic - e.g, if you use toString() as the key to a key-value store. If it is simply used for debugging/logging. Just print out all the fields. e.g, something like what MoreObjects.toStringHelper() does.
The Java API documentation, every recent version I have checked, says:
Returns:
a string representation of the object.
In other words null is not a defined return value. If you don't override the toString() method then you will always get a string that at least gives you the Object's ID.
Although this does not rule out that possibility of an overriding method returning null, any programmer who does this should expect a lot of NPEs from tools and frameworks that might be operating on that code.
My opinion: don't do it.
My question: what kind of object could not be represented by a string?
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
I am wondering if I can use for each loop to iterate through the object of a class. for instance, I created an object honda of type car. I append all the state of the car such as model, price, color, etc. to it. I want to print all the instance of the car. I don't want to use the print statement to print each instance . what is the best way to do it? Thanks.
Below is my java code
package classandobjects;
public class MainClass {
public static void main(String[] args) {
Classes friend1 = new Classes();
friend1.name="yusuf";
friend1.age=27;
friend1.country="Nigeria";
friend1.department="EE";
friend1.gender="male";
Classes friend2 = new Classes();
friend1.name="mathew";
friend1.age=30;
friend1.country="Nigeria";
friend1.department="EE";
friend1.gender="male";
FavPlayers player = new FavPlayers();
player.pname="J.Terry";
player.position="C.Back";
player.gaols=38;
player.awards="25-awards";
FavPlayers player1 = new FavPlayers();
player1.pname="F.Lampard";
player.position="Midfield";
player.gaols=50;
player.awards="10-awards";
Car model = new Car();
model.modelName="Honda Civic";
model.color="Ash-color";
model.Doors="4-doors";
model.price=900000;
System.out.println("below is my friend information");
System.out.println(friend1.name);
System.out.println(friend1.age);
}
}
You had better override a toString method in the Car class and simply print it like:
System.out.println(model);
Indeed, you needn't print each instance variable separately. Your toString may have the following view:
public #Override String toString() {
return modelName + " [" + color + ... + "]"; // also consider StringBuilder
}
If you came from languages where an object is an associative array (e.g. JavaScript) and asked how to print an instance using a foreach loop in Java, then the answer is that Java doesn't allow it (it is possible by reflection though) and you cannot iterate over object variables through a foreach.
I don't want to use the print statement to print each instance
Well, you're going to have to build up a string and print it somewhere.
what is the best way to do it?
If I understand correctly, you want to print an object?
Then implement a toString() method.
public class Classes {
// other code
public String toString() {
// change how you want
return this.name + ", " + this.age;
}
}
Then you can do
System.out.println(friend1);
If you want to print a list of objects, then you need a list to loop over. You could use reflection to get a list of object fields and values, but that seems unnecessary.
This question already has answers here:
Why to use Polymorphism?
(13 answers)
What are the original reasons for ToString() in Java and .NET?
(4 answers)
Closed 8 years ago.
When we need a String representation of an object, we can override the toString() method. However, what are the real benefits and reasons for overriding toString() when we can just define a new method to return the string?
Please see example below:
class One
{
private String name;
public One(String _name)
{
name = _name;
}
#Override public String toString()
{
return name;
}
}
class Two
{
private String name;
public Two(String _name)
{
name = _name;
}
public String printMyClass() //Self-defined to print class details
{
return name;
}
}
In the above example, printMyClass() which is self-defined seemed to does the same thing as toString().
So my question is: Why do we still use toString() ?
The main benefits are that libraries expect this behaviour and use it.
If for example you log "funcX called with ("+param1+", "+param2+")" then toString() will automatically be called for you.
Additionally this means that you always know that the toString() method is available (since it is defined in so you can call it on every object without needing to worry about whether it is present or not.
A better question for you is why not use it? It's provided for you so why do you not want to use it?
Easy conversion to String type that is used in String concatenation with + operator.
The benefit is that you don't have to write printMyClass() multiple times.
This is shorter
obj1 + " " + obj2
than this
obj1.printMyClass() + " " + obj2.printMyClass()
I do sometimes use it to help debugger show more readable output, but that's a little eccentric.
Because toString is used by all other Java code to get a String representation of the Object.
Consider, for example, parametrised logging in SLF4j, here we use a format String and arguments to create a logging statement:
log.info("User {} has just logged in.", user);
The logging library will, if the logging level is low enough, take the format String and call toString on user in order to get the final logging message.
This is just one example of something that can generally be called a "call back". Since toString is part of the Java API many libraries use it to convert an Object to String. Doing the same, for example, deferred evaluation logging, would have required aninterface` and an anonymous class (pre Java 8) which is very messy.
In the most simple example consider String concatenation and implicit String conversion:
final String string = "User is " + user;
Without the toString method how would this even be possible?
This question already has answers here:
Java arrays printing out weird numbers and text [duplicate]
(10 answers)
Closed 8 years ago.
I am switching over from C to java programming gradually. While doing so I am confused while understanding the following scenario:
I have following Java Code:
ArrayList<Integer> myList = new ArrayList<Integer>();
for(int j = 0 ; j < 10 ;j++){
myList.add(j);
}
System.out.println(myList);
the o/p is:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
According to my understanding what I have here is an object(myList) of type ArrayList.
Now I tried to do the same with an Array object: The same code but replacing Arraylist with an Array:
int [] Arr = new int[]{1,2,3,4,5,6,7,8,9,10};
System.out.println(Arr);
I get Garbage values. Why is this so? What is the difference between Array and ArrayList?
As in C , the name of the array is sort of a pointer. (IT has the address of the first element) , So in Java , what does the mere names of the object imply ?
Address or Reference ?
What is the difference?
Why do I get varied results in case of Array and ArrayList?
Although all parts of the question have been answered in different posts, I'd like to address your specific wording.
First, it is recommended that you declare your list type as an interface and initialize it as an implementation:
List<Object> list = new ArrayList<Object>();
List<Object> list = new ArrayList<>(); // JDK 7 or later allows you to omit the generic type.
You can implement a List interface with several implementations (ArrayList, LinkedList...). See the collection tutorial.
What is the difference between Array and ArrayList?
ArrayList is a class, see the API. it serves as an implementation for the List interface, see the API. These are part of the Java Collections Framework.
An array is not a class as the ArrayList is, but both an array and an instance of a class are objects. Be careful with uppercasing Array, as it is a different class.
I get garbage values. Why is this so?
Why do I get varied results in case of Array and ArrayList?
This has to do with the println method. It automatically calls the toString method of the argument passed into it. The toString method is defined for the Object class which superclasses all other classes, thus they all inherit it. Unless the subclass overrides the inherited method, it retains the implementation of its superclass. Let's look at what it does for Object:
public String toString()
Returns a string representation of the
object. In general, the toString method returns a string that
"textually represents" this object. The result should be a concise but
informative representation that is easy for a person to read. It is
recommended that all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the
class of which the object is an instance, the at-sign character `#',
and the unsigned hexadecimal representation of the hash code of the
object. In other words, this method returns a string equal to the
value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
Emphasis mine. As you can see, that's the "garbage" you get when printing the array variable. Since arrays are not classes, they cannot override this method (arrays can invoke all the methods of Object, although they don't subclass it in the usual way). However, the subclass AbstractCollection of Object overrides this:
public String toString()
Returns a string representation of this
collection. The string representation consists of a list of the
collection's elements in the order they are returned by its iterator,
enclosed in square brackets ("[]"). Adjacent elements are separated by
the characters ", " (comma and space). Elements are converted to
strings as by String.valueOf(Object).
Since ArrayList is a subclass of AbstractList, which is a subclass of AbstractCollection (and they do not override toString), you get the "concise but informative representation that is easy for a person to read".
There are some fine points as to how the JVM handles arrays, but for the sake of understanding the output from the developer's point of view, this is enough.
In java, a name of a variable is a reference to the variable (if we compare to c++). When you call println on myList you in-fact call the toString() method of ArrayList which is inherited from Object but overridden to give meaningful print. This method is inherited from Object because ArrayList is a class and all classes extend Object and thus have the method toString.
You don't have this trait with native arrays which are primitives so what you get is the default object representation (virtual memory address).
You can try something like this:
public class TestPrint {
private String name;
private int age;
public TestPrint(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name;}
public int getAge() { return age; }
}
Then try println(new TestPrint("Test", 20)); - This will print something similar to what you got with the array.
Now, add a toString() method:
#Override
public String toString() {
return "TestPrint Name=" + name + " Age=" + age;
}
And call println(new TestPrint("Test", 20)); again and you'll get TestPrint Name=Test Age=20 as the output.
Just to further explain why this happens - the method println has an overload that accepts something of type Object. The implementation of this method calls toString to print the object (this is very schematic explanation of course).
In Java everything is a pointer, but depending on what a variable is pointing, the behavior can change.
int[] Arr = new int[]{1,2,3,4,5,6,7,8,9,10};
int[] is an array of a primitive type (not of a class type), and it does not contains any information about its 'string representation', so when you want to print the variable as you have done (System.out.println(Arr);), what is printed out it is simply a string representation suitable for any kind of object, like its hashcode (it is not garbage).
While with:
ArrayList<Integer> myList = new ArrayList<Integer>();
you are creating an object of the (generic) class ArrayList<>: this overrides the method (function in C) toString() that specify how print gracefully the content of the ArrayList itself (the method is really basic: it simply iterate over all the items contained, create a string and print it).
When you call System.out.println(myList); the method toString() (which return a String) is implicitly called, and therefore the string created by the method will be printed, as you have shown.