Trouble using HashMap containing Objects - java

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());

Related

how can I return a String?

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.

Java: beginner help getting variable

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;
}

Java code output is weird? [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed last month.
I do not understand why my output is not what I expected, instead of showing the persons information, the output displays: examples.Examples#15db9742
Am I doing something wrong in my code?
package examples;
public class Examples {
String name;
int age;
char gender;
public Examples(String name, int age, char gender){
this.name = name;
this.age = age;
this.gender = gender;
}
public static void main(String[] args) {
Examples[] person = new Examples[10];
person[0] = new Examples("Doe",25,'m');
System.out.println(person[0]);
}
}
Add a toString() method to your class:
public class Examples {
String name;
int age;
char gender;
public Examples(String name, int age, char gender){
this.name = name;
this.age = age;
this.gender = gender;
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(this.name + " ");
result.append(this.age + " ");
result.append(this.gender + " ");
return result.toString();
}
public static void main(String[] args) {
Examples[] person = new Examples[10];
person[0] = new Examples("Doe",25,'m');
System.out.println(person[0]);
}
}
When you say
System.out.println(person[0]);
java doesn't automatically know what you want printed out. To tell it, you write a method in your Examples class called toString() which will return a string containing the info you want. Something like:
#Override
public String toString() {
return "Name: " + name +
" Age: " + String.valueOf(this.age) +
" Gender: " + String.valueOf(this.gender);
}
Java has no way of knowing what you want it to print. By default, the toString() method is called when you use System.out.println() with an object.
Your Examples class should have its own toString() method so you can decide what to print. The default toString() returns a representation of the object in memory.
For example, to print out the object's name:
package examples;
public class Examples {
...
#Override
public String toString() {
return name;
}
}
Your output is right, when you print an object the method toString() of the object is called; by default it returns what you see (the class and a memory direction).
Override the method toString() of the class to make him return a descriptive String. E.g.:
public class Examples {
// The same ...
public String toString(){
return "My name is " + name + " and I have " + age + " years."
}
// The same ...
}
If you do that you will get a more descriptive String when calling toString() and so when printing an object of class Examples.
New output is
My name is Dow and I have 25 years.
person is an array of type Examples, so by acessing person[0] you are telling it to print an Examples instance. Since the Examples class does not implement an toString() method it will call the parent Object.toString() method that produces the output you are seeing.
Add the following method to your Examples class
public String toString() {
return "[name="+this.name+", age="+this.age+", gender="+this.gender+"]";
}
You have explicitly to create a method which outputs the persons data or override the toString() method to do the same thing:
public class Person
{
String name;
int age;
char gender;
public Person(String name, int age, char gender)
{
this.name = name;
this.age = age;
this.gender = gender;
}
//Override the toString() method
//is a usual programming technique
//to output the contents of an object
public String toString()
{
return "Name: " + this.name + "\nAge: " + this.age + "\nGender: "
+ this.gender;
}
//You can also write something like this
public void showInfo()
{
System.out.printf("Persons Info:\n\nName: %s\nAge: %s\nGender: %s", this.name, this.age, this.gender);
}
public static void main(String[] args)
{
Person p = new Person("bad_alloc", 97, 'm');
//System.out.println("Persons info:\n" + p.toString());
//If you want directly to "output the object" you have to override the toString() method anyway:
//System.out.println(p);//"Outputting the object", this is possible because I have overridden the toString() method
p.showInfo();
}
}

How to display an object that with multiple parameters without a getter?

In this homework of mine, in my main I have this line:
Lec.addStudent( "James" , "A1" , "BICT" );
In another class called LectureRoom:
import java.util.ArrayList;
public class LectureRoom{
private String courseName;
private String roomNumber;
private String Lecturer;
private ArrayList <Student> studentList;
public LectureRoom(String roomNumber , String courseName , String Lecturer)
{
this.courseName=courseName;
this.roomNumber=roomNumber;
this.Lecturer = Lecturer;
this.studentList = new ArrayList<Student>();
}
public void printStudents(){
System.out.println(studentList);
}
public void addStudent(String name, String id, String major)
{
Student s = new Student(name, id , major);
studentList.add(s);
}
public ArrayList<Student> getStudentsByMajor(String major)
{
ArrayList<Student> students = new ArrayList<>();
for (Student student : studentList) {
if (student.getMajor().equals(major))
students.add(student);
}
return students;
}
The outcome is to be:
Adding:James, A1, BICT
Normally, with a getter I would:
System.out.println("Adding:" + getStudentName() + ", " + getID() + ", " + getMajor() );
However in this case in method addStudent, I have created an object called "s" where it stores the name of the student, id and major.
Suppose I want to print all these 3 in a line, how can I do so?
I tried these in printStudents() method
1) System.out.println(studentList);
2) for(Student studentdetails : studentList)
{
System.out.println(studentdetails);
}
but both returned-
[Student#bf5743]
What is this error called and how can I solve it? Thanks!
You need to Override toString method in your class, and
#Override
public String toString() {
return String.format();// print your desired format.
}
Using System.out.println(obj) directory will print use the default toString method which returns:
object.getClass().getName() + "#" + Integer.toHexString(object.hashCode())
There are more solutions for this problem, but a quite simple one, could be overriding the method toString()
#Override
public String toString() {
return String.format("%s %s %s", s, id, major);
}
I'm assuming that your Student class has the attributes s, id and major that contain student name, id and major.
Have a look at the API for the Object class
Every class has Object as a superclass so your Student class under the covers basically extends Object at some point.
This is important as it means that every accessable method and field in Object is available to your Student class. You can see this in the ide you are using buy doing studentdetails. and see the list that comes up.
If methods in your hierarchy are not final and are accessable you can override them and add your own implementation.

java - return object value

Hi i have the following code:
public List<Person> findAll() {
List<Person> copy = new ArrayList<Person>();
for (Person person : personer) {
copy.add(person);
}
return copy;
}
But when i test this i only retrieve the following and not the value:
[Person#15c7850, Person#1ded0fd,
Person#16a9d42]
How do i get the values and not like above. Where i am inserting the person the code looks like this:
public boolean insert(String name, String nbr) {
if (containsName(name)) {
return false;
}
Person person = new Person(name, nbr);
personer.add(person);
return true;
}
and here is my Person class:
class Person {
private String name;
private String nbr;
public Person (String name, String nbr) {
this.name = name;
this.nbr = nbr;
}
public String getName() {
return name;
}
public String getNumber() {
return nbr;
}
}
You're already receiving the objects you want.
What you see is an internal representation of these objects.
You must iterate through them and call their respective methods to see the information you probably want to see.
If you're not satisfied with these results, you must override toString to provide you with more meaningful information.
Update:
after seeing your edit, you should add toString similar to this one in your Person class:
#Override
public String toString() {
return "Name: " + name + ", number: " + nbr;
}
By the way, you're storing nbr as a string, and it's obvious it should be an integer. So, I'd suggest changing its type to an int or Integer.
You are getting a List object back. You can use the Person object to get the data that you need. To get to the Person objects, iterate over the list.
List<Person> people = findAll();
for Person p : people {
String phoneNumber = p.phoneNumber();
String name = p.Name();
}
Override the toString() method in the Person class if you want a better description when printing the results.
Put something like this in the class Person (don't change the method name!):
public String toString() {
return name;//change this line
}
You are printing out an Object that has the default toString inherited from the Object class. This will print out the type of object it is and its location in memory (ie: Person#1ded0fd).
If you'd like it to see something else, you can override the toString method within your class:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public String toString() {
return this.name;
}
}
If your class looked like the above, this would allow you to do something like this:
Person p = new Person("John");
System.out.println(p);
> John
You can also just grab it as is and print out any information you want from it without overriding the toString method.
Person p = new Person("John");
System.out.println(p.getName());
> John
What value or class Person's property you aspect to retrieve from the ArrayList? This kind of value(Person#15c7850, etc) shows that the Person's object random id that assigned by JVM when you use
System.out.print(copy).

Categories

Resources