Please pardon my bad English
I am trying to create a HashMap with a String as a key, and an Object as parameter, which I want to initialise each time the program runs so that its added to a new key in the HashMap.
The problem is, that not all values are returned, and namely the second, gives back a weird output.
package javaex1;
import java.util.*;
public class Javaex1 {
public static void main(String[] args) {
Person obj = new Person("Eminem", "Male");
HashMap<String, Person> MapPerson = new HashMap<String, Person>();
MapPerson.put("Eminem", obj);
System.out.println(MapPerson);
}
}
The object
package javaex1;
public class Person {
String Name;
String Gender;
public Person (String name, String Gend) {
this.Name = name;
this.Gender = Gend;
}
public String getName() {
return Name;
}
public String getGender() {
return Gender;
}
}
Any help or hint is greatly appreciated! Thank you in advance for your time!
The expected results should be "Eminem Male". Instead what I get is this:
{Eminem=javaex1.Person#2a139a55}
This happens because you are trying to print an Object, An Object when printed gives the default toString implementaion of Object class , which is shown below
// implementation of toString in Object class
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
This is what you can see in your current output .
You should ovverride toString method in Person class like this.
public String toString() {
return this.Name + " " + this.Gender;
}
So that it returns the name and gender
You should override toString method in Person class. Like that:
#Override
public String toString() {
return this.Name + " " + this.Gender;
}
You're printing the MapPerson object, not the Person one.
Your code should be:
Person person = MapPerson.get("Eminem");
System.out.println(person.getName() + " " + person.getGender());
Have to code a player class in java eclipse following these requirements
a) The Player class should have a default constructor and two custom constructors - one
that accepts a Name object, and another that accepts both a Name and PairOfDice object.
b) There should be get and set methods for its Name and a get method for PairOfDice. It
should have a method called rollDice and getDiceScore that both simply delegate to the
PairOfDice class, which already has this functionality. You should also have an
appropriate toString() method.
c) Add a further void method setFullPlayerName(String) that accepts a single String
argument (e.g. “Joe Bloggs”) and then uses this to set the first and family name
individually by extracting the relevant information and then calling the respective setter
methods of the Name class.
So far I have this
public class Player {
//Fields of the app
private String firstName;
private String lastName;
private Die red;
private Die blue;
//PlayerName and dice pair Default Constructor
public Player() {
firstName = "";
lastName = "";
red = new Die();
blue = new Die();
}
public Player(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public Player(String firstName, String lastName,Die red,Die blue) {
this.firstName = firstName;
this.lastName = lastName;
this.red = red;
this.blue = blue;
}
// Methods
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setlastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getlastName() {
return lastName;
}
#Override
public String toString() {
return "PairOfDice:[red=" + red + ", blue=" + blue + "]";
}
public void rollDice() {
red.roll();
blue.roll();
}
public int getDiceScore() {
return red.getScore() + blue.getScore();
}
public Die getRed() {
return red;
}
public Die getBlue() {
return blue;
}
public String setFullName() {
if (firstName.equals("") && lastName.equals("")) {
return "";
} else {
return firstName + " " + lastName;
}
}
}
Is my code correct? if not what changes do i have to make to correct it
There are several problems:
Dice not Die: private Die red;
It's better to name your variable using a noun: private Dice redDice;
Should have a space after a comma: , Dice redDice, Dice blueDice
setFullName should accept 1 string and call setFirstName and setLastName to set the name
Example of implementation:
void setFullName(String fullName) {
/// split full name into lastName and firstName
setFirstName(firstName);
setLastName(lastName);
}
Everything seems fine, but I think you forgot to define the roll() function. Besides that, everything else seems fine :)
I see a couple of issues with this code:
a) The Player class should have a default constructor and two custom constructors - one that accepts a Name object, and another that accepts both a Name and PairOfDice object.
b) There should be get and set methods for its Name and a get method for PairOfDice. It should have a method called rollDice and getDiceScore that both simply delegate to the PairOfDice class, which already has this functionality. You should also have an appropriate toString() method.
If it's telling you that you need a Name object and a PairOfDice object, you can't just put in two Strings and two Dies and call that the same thing. You need to actually use the Name and PairOfDice classes.
c) Add a further void method setFullPlayerName(String) that accepts a single String argument (e.g. “Joe Bloggs”) and then uses this to set the first and family name individually by extracting the relevant information and then calling the respective setter methods of the Name class
Instead of setFullPlayerName, you made a method called setFullName that does not do what it's supposed to do. It's supposed to accept a String and return void, and instead it accepts no parameters and returns a String. It looks like a getter instead of a setter.
Let's get this straight: This portion of the code:
public String setFullName() {
if (firstName.equals("") && lastName.equals("")) {
return "";
} else {
return firstName + " " + lastName;
}
}
it's misleading due to the fact that the method name it's saying that it's setting the name, BUT you're returning the name instead
So change it to this:
public void setFullPlayerName(String name) {
String[] splitted = name.split(" ");
firstname = splitted[0];
lastname = splitted[1]
}
And now it's unnecessary to add the method setFullPlayerName
BUT I see that you may need a method to return a full name, so:
public String getFullPlayerName() {
return firstname + " " + lastname;
}
Hopefully that'll resolve your issue :D
package book1;
import java.util.ArrayList;
public abstract class Book {
public String Book (String name, String ref_num, int owned_copies, int loaned_copies ){
return;
}
}
class Fiction extends Book{
public Fiction(String name, String ref_num, int owned_copies, String author) {
}
}
at the moment when i input values into the variable arguments and call them with this :
public static class BookTest {
public static void main(String[] args) {
ArrayList<Book> library = new ArrayList<Book>();
library.add(new Fiction("The Saga of An Aga","F001",3,"A.Stove"));
library.add(new Fiction("Dangerous Cliffs","F002",4,"Eileen Dover"));
for (Book b: library) System.out.println(b);
System.out.println();
}
}
i get a return value of this:
book1.Fiction#15db9742
book1.Fiction#6d06d69c
book1.NonFiction#7852e922
book1.ReferenceBook#4e25154f
how can i convert the classes to return a string value instead of the object value? I need to do this without changing BookTest class. I know i need to use to string to convert the values. but i don't know how to catch the return value with it. could someone please point me in the right direction on how to convert this output into a string value?
You need to overwrite the toString() Method of your Book class. In this class you can generate a String however you like. Example:
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.author).append(": ").append(this.title);
return sb.toString();
}
You need to override the toString() method in your Book or Fiction class. The method is actually declared in the Object class, which all classes inherit from.
#Override
public String toString(){
return ""; // Replace this String with the variables or String literals that you want to return and print.
}
This method is called by System.out.println() and System.out.print() when they receive an object in the parameter (as opposed to a primitive, such as int and float).
To reference the variables in the method, you'll need to declare them in the class and store them via the class's constructor.
For example:
public abstract class Book {
private String name;
private String reference;
private int ownedCopies;
private int loanedCopies;
public Book (String name, String reference, int ownedCopies, int loanedCopies) {
this.name = name;
this.reference = reference;
this.ownedCopies = ownedCopies;
this.loanedCopies = loanedCopies;
}
#Override
public String toString(){
return name + ", Ref:" + reference + ", OwnedCopies: " + ownedCopies + ", LoanedCopies: " + loanedCopies; // Replace this String with the variables or String literals that you want to return and print.
}
}
The classes you have defined, don't store any values. It is in other words useful to construct a new book. You need to provide fields:
public abstract class Book {
private String name;
private String ref_num;
private int owned_copies;
private int loaned_copies;
public String Book (String name, String ref_num, int owned_copies, int loaned_copies) {
this.name = name;
this.ref_num = ref_num;
this.owned_copies = owned_copies;
this.loaned_copies = loaned_copies;
}
public String getName () {
return name;
}
//other getters
}
Now an object is basically a set of fields. If you want to print something, you can access and print one of these fields, for instance:
for (Book b: library) System.out.println(b.getName());
In Java, you can also provide a default way to print an object by overriding the toString method:
#Override
public String toString () {
return ref_num+" "+name;
}
in the Book class.
Need to give your object Book a ToString() override.
http://www.javapractices.com/topic/TopicAction.do?Id=55
Example:
#Override public String toString()
{
return name;
}
Where name, is a string in the Class.
I am hoping that you have assigned the passed arguments to certain attributes of the classes. Now, once you are done with that, you can override the toString() method in Book to return your customized string for printing.
This is for a school project. I have built a simple class with 3 string variables and a constructor to fill these fields.
public class Names {
String firstName;
String middleName;
String lastName;
public Names(String name){
System.out.println("Passed name is: " + name);
}
public void setFirstName(String name){
firstName = name;
}
public void setMiddleName(String name){
middleName = name;
}
public void setLastName(String name){
lastName = name;
}
public static void main(String []args){
Names drew = new Names("Drew");
drew.setFirstName("Drew");
drew.setMiddleName("Leland");
drew.setLastName("Sommer");
System.out.println(drew.firstName + " " + drew.middleName + " " + drew.lastName);
}
public getFirstName(String name){
}
public getMiddleName(String name){
}
public getLastName(String name){
}}
At the bottom where it is getFirstName, getMiddleName, getLastName I want to be able to pass something like getFirstName(drew) and have it return drew.firstName?
I am very new to java FYI.
These are "getter" methods to return the values of instance fields. drew is your current Names instance here, therefore if you call these methods on this instance, you'll receive the values you've set with your "setter" methods. And since you're calling them on a specific instance, you don't need to pass it as a method argument. That is why these getter methods are normally parameterless.
They should look like this:
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
Please note that I've added the corresponding return type (String), because the data type of each instance field is String.
Your println call in the main method would then look like this:
System.out.println(drew.getFirstName() + " " + drew.getMiddleName() + " " + drew.getLastName());
public String getFirstName() {
return this.firstName;
}
This will return the firstName of the object you call it on.
You can call it like this:
System.out.println(drew.getFirstName() + " " + drew.middleName + " " + drew.lastName);
You can then do the same thing for getMiddleName and getLastName.
Your get methods will be called by an instance of your Names class. When you create an instance of the class and assign it a variable name, just use that variable name to call the method and it will return the name for that instance.
//Instantiate the Names class
Names drew = new Names("Drew");
//Call methods to set the names
drew.setFirstName("Drew");
drew.setMiddleName("John");
drew.setLastName("Smith");
//Call methods to get the names
drew.getFirstName(); //Returns "Drew"
drew.getMiddleName(); //Returns "John"
drew.getLastName(); //Returns "Smith"
And, like others suggested, your get / set methods should be like this:
public void setFirstName(String n){
firstName = n;
}
public String getFirstName(){
return firstName;
}
as you said, "I want to be able to pass something like getFirstName(drew) and have it return drew.firstName"
so the impl is simple,
public String getFirstName(Names other) {
return other.firstName;
}
Can anybody explain to me the concept of the toString() method, defined in the Object class? How is it used, and what is its purpose?
From the Object.toString 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.
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())
Example:
String[] mystr ={"a","b","c"};
System.out.println("mystr.toString: " + mystr.toString());
output:- mystr.toString: [Ljava.lang.String;#13aaa14a
Use of the String.toString:
Whenever you require to explore the constructor called value in the String form, you can simply use String.toString...
for an example...
package pack1;
import java.util.*;
class Bank {
String n;
String add;
int an;
int bal;
int dep;
public Bank(String n, String add, int an, int bal) {
this.add = add;
this.bal = bal;
this.an = an;
this.n = n;
}
public String toString() {
return "Name of the customer.:" + this.n + ",, "
+ "Address of the customer.:" + this.add + ",, " + "A/c no..:"
+ this.an + ",, " + "Balance in A/c..:" + this.bal;
}
}
public class Demo2 {
public static void main(String[] args) {
List<Bank> l = new LinkedList<Bank>();
Bank b1 = new Bank("naseem1", "Darbhanga,bihar", 123, 1000);
Bank b2 = new Bank("naseem2", "patna,bihar", 124, 1500);
Bank b3 = new Bank("naseem3", "madhubani,bihar", 125, 1600);
Bank b4 = new Bank("naseem4", "samastipur,bihar", 126, 1700);
Bank b5 = new Bank("naseem5", "muzafferpur,bihar", 127, 1800);
l.add(b1);
l.add(b2);
l.add(b3);
l.add(b4);
l.add(b5);
Iterator<Bank> i = l.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
}
... copy this program into your Eclipse, and run it... you will get the ideas about String.toString...
The toString() method returns a textual representation of an object. A basic implementation is already included in java.lang.Object and so because all objects inherit from java.lang.Object it is guaranteed that every object in Java has this method.
Overriding the method is always a good idea, especially when it comes to debugging, because debuggers often show objects by the result of the toString() method. So use a meaningful implementation but use it for technical purposes. The application logic should use getters:
public class Contact {
private String firstName;
private String lastName;
public Contact (String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {return firstName;}
public String getLastName() {return lastName;}
public String getContact() {
return firstName + " " + lastName;
}
#Override
public String toString() {
return "["+getContact()+"]";
}
}
It may optionally have uses within the context of an application but far more often it is used for debugging purposes. For example, when you hit a breakpoint in an IDE, it's far easier to read a meaningful toString() of objects than it is to inspect their members.
There is no set requirement for what a toString() method should do. By convention, most often it will tell you the name of the class and the value of pertinent data members. More often than not, toString() methods are auto-generated in IDEs.
Relying on particular output from a toString() method or parsing it within a program is a bad idea. Whatever you do, don't go down that route.
toString() returns a string/textual representation of the object.
Commonly used for diagnostic purposes like debugging, logging etc., the toString() method is used to read meaningful details about the object.
It is automatically invoked when the object is passed to println, print, printf, String.format(), assert or the string concatenation operator.
The default implementation of toString() in class Object returns a string consisting of the class name of this object followed by # sign and the unsigned hexadecimal representation of the hash code of this object using the following logic,
getClass().getName() + "#" + Integer.toHexString(hashCode())
For example, the following
public final class Coordinates {
private final double x;
private final double y;
public Coordinates(double x, double y) {
this.x = x;
this.y = y;
}
public static void main(String[] args) {
Coordinates coordinates = new Coordinates(1, 2);
System.out.println("Bourne's current location - " + coordinates);
}
}
prints
Bourne's current location - Coordinates#addbf1 //concise, but not really useful to the reader
Now, overriding toString() in the Coordinates class as below,
#Override
public String toString() {
return "(" + x + ", " + y + ")";
}
results in
Bourne's current location - (1.0, 2.0) //concise and informative
The usefulness of overriding toString() becomes even more when the method is invoked on collections containing references to these objects. For example, the following
public static void main(String[] args) {
Coordinates bourneLocation = new Coordinates(90, 0);
Coordinates bondLocation = new Coordinates(45, 90);
Map<String, Coordinates> locations = new HashMap<String, Coordinates>();
locations.put("Jason Bourne", bourneLocation);
locations.put("James Bond", bondLocation);
System.out.println(locations);
}
prints
{James Bond=(45.0, 90.0), Jason Bourne=(90.0, 0.0)}
instead of this,
{James Bond=Coordinates#addbf1, Jason Bourne=Coordinates#42e816}
Few implementation pointers,
You should almost always override the toString() method. One of the cases where the override wouldn't be required is utility classes that group static utility methods, in the manner of java.util.Math. The case of override being not required is pretty intuitive; almost always you would know.
The string returned should be concise and informative, ideally self-explanatory.
At least, the fields used to establish equivalence between two different objects i.e. the fields used in the equals() method implementation should be spit out by the toString() method.
Provide accessors/getters for all of the instance fields that are contained in the string returned. For example, in the Coordinates class,
public double getX() {
return x;
}
public double getY() {
return y;
}
A comprehensive coverage of the toString() method is in Item 10 of the book, Effective Java™, Second Edition, By Josh Bloch.
Whenever you access an Object (not being a String) in a String context then the toString() is called under the covers by the compiler.
This is why
Map map = new HashMap();
System.out.println("map=" + map);
works, and by overriding the standard toString() from Object in your own classes, you can make your objects useful in String contexts too.
(and consider it a black box! Never, ever use the contents for anything else than presenting to a human)
Correctly overridden toString method can help in logging and debugging of Java.
Coding:
public class Test {
public static void main(String args[]) {
ArrayList<Student> a = new ArrayList<Student>();
a.add(new Student("Steve", 12, "Daniel"));
a.add(new Student("Sachin", 10, "Tendulkar"));
System.out.println(a);
display(a);
}
static void display(ArrayList<Student> stu) {
stu.add(new Student("Yuvi", 12, "Bhajji"));
System.out.println(stu);
}
}
Student.java:
public class Student {
public String name;
public int id;
public String email;
Student() {
}
Student(String name, int id, String email) {
this.name = name;
this.id = id;
this.email = email;
}
public String toString(){ //using these toString to avoid the output like this [com.steve.test.Student#6e1408, com.steve.test.Student#e53108]
return name+" "+id+" "+email;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email=email;
}
}
Output:
[Steve 12 Daniel, Sachin 10 Tendulkar]
[Steve 12 Daniel, Sachin 10 Tendulkar, Yuvi 12 Bhajji]
If you are not used toString() in Pojo(Student.java) class,you will get an output like [com.steve.test.Student#6e1408, com.steve.test.Student#e53108].To avoid these kind of issue we are using toString() method.
Apart from what cletus answered with regards to debugging, it is used whenever you output an object, like when you use
System.out.println(myObject);
or
System.out.println("text " + myObject);
The main purpose of toString is to generate a String representation of an object, means the return value is always a String. In most cases this simply is the object's class and package name, but on some cases like StringBuilder you will got actually a String-text.
/**
* This toString-Method works for every Class, where you want to display all the fields and its values
*/
public String toString() {
StringBuffer sb = new StringBuffer();
Field[] fields = getClass().getDeclaredFields(); //Get all fields incl. private ones
for (Field field : fields){
try {
field.setAccessible(true);
String key=field.getName();
String value;
try{
value = (String) field.get(this);
} catch (ClassCastException e){
value="";
}
sb.append(key).append(": ").append(value).append("\n");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return sb.toString();
}
If you learn Python first and then Java. I think it plays the same role as __str__() method in Python, it is a magic method like __dict__() and __init__() but to refer to a string representing the the object.
the toString() converts the specified object to a string value.