I created a HashMap where the keys are Integers and the values are of the Employee class. Employee contains the employee's first name, last name and address. I am having issues with printing out the values. Here is what i tried.
employees.put(5, e1);
String test=employees.get(5).toString();
System.out.println(employees.toString());
System.out.println(test);
output:
{5=identitymanagement.Employee#6da264f1}
identitymanagement.Employee#6da264f1
What am I doing wrong?
A look at your code
String test=employees.get(5).toString();
This will grab the item with the key 5 in your hashmap, then call that object's toString method. The way your object is behaving at the moment implies you have no overridden that method, which is why it is printing out the objects address in memory.
System.out.println(employees.toString());
This will attempt to print out the HashMap object. In the same vain as your Employee class, HashMap does not override it's toString method, so it simply prints out the objects reference in memory.
A solution
The convention, when outputting the details of a class, is to override the toString() method. This would look something like this:
public String toString()
{
return "name: " + name;
}
When you place this method in your class, you can call the toString method and it won't just print out the memory address of the object, which is what it is doing at the moment :)
When using this code, all you have to do is pass the object to the System.out.println method and it will do the rest:
Employee e = employees.get(5);
System.out.println(e);
The correct way is
Employee e = employees.get(5); // return's Employee object stored in map with key 5
String firstName = e.firstName;
String lastName = e.lastName;
String address = e.address;
Related
#Entity
public class Person {
private Integer id = null;
private String name = null;
private String price = null;
private Date created = null;
// String Representation:
#Override
public String toString() {
return name;
// I want to return name and price
}
I want to return name and price in toString function ? This is right to return more than one string in toString function. If you make relation in other's Entity ManyToMany ?
Please suggest me if I am doing right or wrong as I want to show these fields in other entity where I make relations.
Thanks!
Usually the toString() method returns a string-representation of the object and not the object's members themself. So if you need a representation of name and price you could do
return "Name: " + name + ", Price: " + price;
If you really want to receive the members name and price you should generate getters for those and use them in the caller.
Another possibility is to "wrap" the two strings in some sort of data class.
This is right to return more than one string in toString function. If you make relation in other's Entity ManyToMany ?
That could be
#Override
public String toString() {
return "Name :" +name + " Price : "+price;
}
If you still have more Objects related to it, just append in the last. So that you won't loose information.
You can do it like this:
return name+" "+price;
You can create another method to return both.
you can return String array as well so that you don't need to split the string if you need to perform any operation on name and price.
You can use a StringBuilder and build up your composed String efficiently from both the name, the price and whatever you want.
Here the documentation.
Anyway, the response is no, you cannot send back two strings, but you can return a string that is a composition of the others.
I am trying to make a method that will create a new unique object based on another class that I have have in the same project. I know that the last line wont compile, but is there a way to accomplish the same goal?
Ideally if the fName=John and lName=Smith, then the new "Employee" object created on the last line would be called "JohnSmith" but the goal is just to create a unique instance of the object every time that the method is called
public static void createEmployee(int number){
Scanner input= new Scanner(System.in);
System.out.printf("Enter first name for employee %s: ",number);
String fName=input.next();
System.out.printf("Enter last name for employee %s: ",number);
String lName=input.next();
Employee fName+lName= new Employee(fName,lName);
}
I am fairly new to Java, and object oriented programming in general so if I am going about this wrong I am open to going about it a different way.
No, what you're describing isn't possible.
As a conceptual exercise, your variables should describe the kind of data they're holding. It may sound pretty plain, but employee would be a better name for that variable than JohnSmith or SteveJobs or any other first + last name combination.
If you're intending to create a new instance of an Employee every time, you should return the Employee instance from the method instead of declaring it void. Then you can use it however you like wherever you call it.
public static Employee createEmployee(int number){
Scanner input = new Scanner(System.in);
System.out.printf("Enter full name of employee %d, separated by spaces: ", number);
String fName = input.next();
String lName = input.next();
return new Employee(fName, lName);
}
You can't do it that way. But remember, many "JohnSmith" exist - you would run into homonyms easily.
If these aren't a problem, you could use a Map to bind a key (The String made with Surname + Name) to a value (your employee).
Good luck and welcome to StackOverflow!
UPDATE
If homonyms are a problem, you will need to use unique IDs; they assure you that you have no overlaps. You could build an ID in the Employee itself, and put them in a List, or you can put them in an Array - the ID will then be their position in the array.
No. You can't combine a variable like that, but you could say something like
// Employee fName+lName= new Employee(fName,lName);
Employee employee = new Employee(fName, lName);
And if Employee overrides toString() then
System.out.println(employee);
should give you the output you would expect.
I second the hashmap. Having a human readable variable name dynamically created is overly complicated. Using a hashmap you can reference the object with a string
HashMap<String, Employee> employees = new HashMap<String, Employee>();
employees.put(fName + lName, new Employee(fName, lName));
To get the employ obj
employees.get(fName + lName);
I have a requirement where i have to print the values which are getting saved in a database. I have pojo object which i am passing it in a list and then saving the entire list in database. Please find the below code.
List dataList=new ArrayList();
Vehicles vehiclePojoObject=new Vehicles();
vehiclePojoObject.setName("Cycle");
vehiclePojoObject.setColor("Blue");
dataList.add(vehiclePojoObject);
Now i have to print the values which is contained by vehiclePojoObject. How can it be acheived. Please guide. Thanks in advance.
Note: There are not one object but multiple objects which are getting stored in the list.
Other than the solution posted by #McMonster, you could also make sure that your POJO's override the toString() method so that you can print a customized, and most likely, more readable string representation of your object.
Add vehiclePojoObject to the Vehicles List object, like
List<Vehicles> vehList = new ArrayList<Vehicles>();
Vehicles vehiclePojoObject=new Vehicles();
vehiclePojoObject.setName("Cycle");
vehiclePojoObject.setColor("Blue");
vehList.add(vehiclePojoObject); //Here we are adding pojoObject to list object
And get Vehicles List data through for-each
i.e.
for(Vehicles vehicle : vehList){
System.out.println("Vehicle Name: "+veh.getName());
System.out.println("Vehicle Color: "+veh.getColor());
}
Expanding on #npinti answer of overriding toString()
In your POJO file, add this function:
#Override
public String toString() {
String output = "Name: " + getName() + " Color: " + getColor +
" Model: " + getModel() + ....;
return output;
}
then you can loop through your list to and call .toString() on all the objects to print out all of the features
for(Vehicles vehicle : vehList){
System.out.println(vehicle.toString());
}
Assuming that you want to store objects of different types on the same list and have a single method for printing all private fields of those object regardless of their types you can use the (reflection API).
By the help of reflection we can change behavior of list at runtime
List dataList = new ArrayList<>();
// Print the name from the list....
for(Vehicles vehicle: Vehicles) {
System.out.println(vehicle.getName());
System.out.println(vehicle.getColor());
}
Hope this helps!!!
I know that the Javadocs says:
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.
But when should I spend time overriding the toString method for my classes? Should it be one of the first things I do along with overriding equals and hashCode? Or should I wait until it's actually needed?
I know Eclipse can auto generate toString methods for you, so should I just have Eclipse auto generate them once I know the fields for my class?
Josh Bloch gives a good explanation in Effective Java, in item 10.
[...] providing a good toString implementation makes your class much more pleasant to use.
It really makes it easier to output debugging traces, or makes better logging messages, since you can use the object's string representation provided by toString() directly; you don't have to manually build a string that gives the information needed on the object.
As stated in the book, you should include all the interesting information in the resulting String. You should also document properly your method; you may document the resulting String format or not, but you should at least document your intent (whether the format is subject to change, or not likely to change).
In the end, it is up to you (and your company's standards) to decide if overriding it in every class should be part of your habits or not. Personally, I don't override toString () in every classes, only in the ones which are most at risk of being used in a debuging trace.
I would implement toString() method on any class that holds human understandable non confidential data. Ex: Transfer Object, Beans, Data Object, Wrappers. For such classes just go on to implement 'toString()' method.
Classes that represent a service, process with transient states need not implement the method.Here, You can wait until it is actually needed.
Make sure you do not expose any variables with "transient" keyword in 'toString()'!
Typically, I override it when I want to assign a default format of displaying an object, often formatting a compact/digestable display of relevant attributes. So that I can simply, for example, display it in debug or log by doing:
MyClass myClsInst = new MyClass();
...
System.out.println(myClsInst);
In general, It's used to show or see what the object has.
For instance, Let's say there is a Student class and you created objects.
Student class has age, grade, gpa, name, country, address.
class Student{
private int age;
private int grade;
private double gpa;
private String name;
private String country;
private String address;
Student(...){
// ...
}
public String toString(){
String str = "age is "+age+ ", grade is " + grade + ...
return str;
}
}
And you created A student, and B student ( and maybe more )
You just need to 'toString()' for checking its inside like this:
System.out.println(aStudent.toString());
System.out.println(bStudent.toString());
or You can just write the object name, it automatically calls 'toString()'
System.out.println(aStudent);
System.out.println(bStudent);
It removes the redundant works & faster.
Then, you will see like this:
Output:
age is 13, grade is 3, ...
age is 15, grade is 5, ...
It's useful when you see what A student or B student has when you debug.
And also, It's useful when you make your own form like JSON.
It will be easier to manipulate its data with JSON format.
I am trying to demonstrate in simple way.
package com.web.doamin;
public class User {
String name;
long id;
/*#Override
public String toString() {
return "User [user = " + name + ", id="+ id + "]";
}*/
public static void main(String[] args) {
User user = new User();
System.out.println(" : user : " + user );
}
}
If we did't Override toString() method we will get Object Hash code in sysout
O/P without Override toString() method - com.web.doamin.User#7852e922
if We Override the ToString() method we will get O/P - User [user = null, id=0]
Note - It is a good idea to override toString() as we get get proper output when an object is used in System.out.println();
I have a HashMap. I am trying to retrieve the value and print it using the key from the user-code.
The code is:
lib.addbook(book2.getISBN(), book2);
Book ret = lib.getbook("978-81-291-1979-7");
System.out.println(ret);
Current Output:
O/P: LibraryPackage.Book#527c6768
I want the output to be a string and to display the actual value not the address of the book.
You have to implement (and override) the toString() method in your Book class, and specify what you want the output to be. E.g.:
#Override
String toString()
{
return this.author+": " + this.title;
}
commons-lang has a great utility for this if you don't want to override the .toString() method, or need to represent it differently in different situations:
Here's a call to build a string based on reflection:
String str = ToStringBuilder.reflectionToString(object);
In fact, this is a great way to implement the .toString() method itself. Another alternative use of this class would be a field by field creation of the string:
String str = new ToStringBuilder(object)
.append("field1", field1)
.append("field2", field2)
.toString();