Getting object values from a LinkedHashMap - java

So for my local data structure I have the following
DataStructure ds = new DataStructure();
//Examples to put in the Data Structure "ds"
ds.menu_item.put("Pizza", new DescItems("A Pizza",2.50,4));
ds.menu_item.put("Hot Dog", new DescItems("A yummy hot dog",3.50, 3));
ds.menu_item.put("Corn Dog", new DescItems("A corny dog",3.00));
ds.menu_item.put("Unknown Dish", new DescItems(3.25));
The DataStructure class has a LinkedHashMap implementation such that
LinkedHashMap<String, DescItems> menu_item = new LinkedHashMap<String, DescItems>();
And finally the DescItems class is
public final String itemDescription;
public final double itemPrice;
public final double itemRating;
public DescItems(String itemDescription, double itemPrice, double itemRating){
this.itemDescription = itemDescription;
this.itemPrice = itemPrice;
this.itemRating = itemRating;
}
There are other constructors to account for no itemDescription and/or itemRating
I'm trying to apply a method to check to see if a value has itemRating other than 0 (0 indicating no rating)
But specifically I came across this problem:
DescItems getC1 = (DescItems)ds.menu_item.get("Pizza");
System.out.println(getC1.toString());
Only prints out reference information like DescItems#142D091
What should I do to get a specific object variable instead of referencing the object?

You need to Override the toString() method in DescItems
Something like this:
#Override
public String toString() {
return itemDescription + " " + itemPrice + currencySymbol + " (" + itemRating + ")";
}

You can override the toString() method in your DescItems class. For example:
public class DescItems {
. . .
#Override
public String toString() {
// whatever you want here
return String.format("%1$s (price: $%2$.2f; rating: %3$f)",
itemDescription, itemPrice, itemRating);
}
}
The default implementation of toString() returns an object identification string like what you are seeing.
An alternative is to print the exact field(s) you want:
System.out.println(getC1.itemDescription);

You just need to override the toString() method to return the text that you want.

Related

How to get Array List to show three indexes at one time in android studio? [duplicate]

Sounds a little stupid, but I need help on my toString() method and it is very irking.
I tried looking up online because the toString is the one where it is screwing up and "not finding Kid constructor #2" even though it is there and I would even do something else and it doesn't work.
Ok that was a lot so here is my code:
import java.util.*;
class Kid {
String name;
double height;
GregorianCalendar bDay;
public Kid () {
this.name = "HEAD";
this.height = 1;
this.bDay = new GregorianCalendar(1111,1,1);
}
public Kid (String n, double h, String date) {
// method that toString() can't find somehow
StringTokenizer st = new StringTokenizer(date, "/", true);
n = this.name;
h = this.height;
}
public String toString() {
return Kid(this.name, this.height, this.bDay);
}
} //end class
Ok So my toString above (I know, my third parameter is off, should be a String) is off. If I hardcode a value in for the third thing it goes haywire and says it can't find this (up above). So how can I get the date and break it up?
Class calling this is below
class Driver {
public static void main (String[] args) {
Kid kid1 = new Kid("Lexie", 2.6, "11/5/2009");
System.out.println(kid1.toString());
} //end main method
} //end class
I tried researching multiple constructors and it really didn't help.
I tried researching toString() methods, and tried using previous toString() methods logic that I created previous but this is brand new so it never worked.
Help?
The toString is supposed to return a String.
public String toString() {
return "Name: '" + this.name + "', Height: '" + this.height + "', Birthday: '" + this.bDay + "'";
}
I suggest you make use of your IDE's features to generate the toString method. Don't hand-code it.
For instance, Eclipse can do so if you simply right-click on the source code and select Source > Generate toString
Java toString() method
If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the string representation of the object.
If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.
Advantage of Java toString() method
By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code.
Output without toString() method
class Student{
int id;
String name;
String address;
Student(int id, String name, String address){
this.id=id;
this.name=name;
this.address=address;
}
public static void main(String args[]){
Student s1=new Student(100,”Joe”,”success”);
Student s2=new Student(50,”Jeff”,”fail”);
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:Student#2kaa9dc
Student#4bbc148
You can see in the above example #1. printing s1 and s2 prints the Hashcode values of the objects but I want to print the values of these objects. Since java compiler internally calls toString() method, overriding this method will return the specified values. Let's understand it with the example given below:
Example#2
Output with overriding toString() method
class Student{
int id;
String name;
String address;
Student(int id, String name, String address){
this.id=id;
this.name=name;
this.address=address;
}
//overriding the toString() method
public String toString(){
return id+" "+name+" "+address;
}
public static void main(String args[]){
Student s1=new Student(100,”Joe”,”success”);
Student s2=new Student(50,”Jeff”,”fail”);
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:100 Joe success
50 Jeff fail
Note that toString() mostly is related to the concept of polymorphism in Java.
In, Eclipse, try to click on toString() and right click on it.Then, click on Open Declaration and see where the Superclass toString() comes from.
As others explained, the toString is not the place to be instantiating your class. Instead, the toString method is intended to build a string representing the value of an instance of your class, reporting on at least the most important fields of data stored in that object. In most cases, toString is used for debugging and logging, not for your business logic (except some historical methods, like Integer.toString()).
To generate text representing the value of an object for display to a user, add another method. People often name the method something like getDisplayName. For example, DayOfWeek::getDisplayName and Month::getDisplayName.
StringJoiner
As of Java 8 and later, the most modern way to implement toString would use the StringJoiner class. As the doc says:
StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.
Use like this:
#Override
public String toString ()
{
return new StringJoiner( // In Java 8 and later, StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.
" | " , // Delimiter
Person.class.getSimpleName() + "[ " , // Prefix
" ]" // Suffix
)
.add( "name=" + name ) // Append
.add( "phone=" + phone ) // Append
.toString(); // Convert entire sequence to a single `String` object.
}
Person[ name=Alice | phone=555.867.5309 ]
record
Java 16 brings a new way to briefly define a class where the main purpose is to communicate data transparently and immutably: record.
You define a record by merely listing the type and name of each member field. The compiler implicitly creates the constructor, getters, equals & hashCode, and toString.
Default implementation of toString
The default implementation of toString includes each and every member field.
public Kid ( String name , double height , LocalDate birthDate ) {}
Instantiate like any other object.
Kid alice = new Kid( "Alice" , 6.1d , LocalDate.of( 2019 , Month.April , 23 ) ) ;
String output = alice.toString() ;
You may choose to override the default implementation with your own. Overrides are usually not needed given the purpose of a record as a simple data-carrier.
You can creating new object in the toString().
use
return "Name = " + this.name +" height= " + this.height;
instead of
return Kid(this.name, this.height, this.bDay);
You may change the return string as required. There are other ways to store date instead calander.
You can't call a constructor as if it was a normal method, you can only call it with new to create a new object:
Kid newKid = new Kid(this.name, this.height, this.bDay);
But constructing a new object from your toString() method is not what you want to be doing.
Following code is a sample. Question based on the same, instead of using IDE based conversion, is there a faster way to implement so that in future the changes occur, we do not need to modify the values over and over again?
#Override
public String toString() {
return "ContractDTO{" +
"contractId='" + contractId + '\'' +
", contractTemplateId='" + contractTemplateId + '\'' +
'}';
}
If you're interested in Unit-Tests, then you can declare a public "ToStringTemplate", and then you can unit test your toString. Even if you don't unit-test it, I think its "cleaner" and uses String.format.
public class Kid {
public static final String ToStringTemplate = "KidName='%1s', Height='%2s', GregCalendar='%3s'";
private String kidName;
private double height;
private GregorianCalendar gregCalendar;
public String getKidName() {
return kidName;
}
public void setKidName(String kidName) {
this.kidName = kidName;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public GregorianCalendar getGregCalendar() {
return gregCalendar;
}
public void setGregCalendar(GregorianCalendar gregCalendar) {
this.gregCalendar = gregCalendar;
}
public String toString() {
return String.format(ToStringTemplate, this.getKidName(), this.getHeight(), this.getGregCalendar());
}
}
Now you can unit test by create the Kid, setting the properties, and doing your own string.format on the ToStringTemplate and comparing.
making ToStringTemplate static-final means "ONE VERSION" of the truth, rather than having a "copy" of the template in the unit-test.
The best way in my opinion is using google gson library:
#Override
public String toString() {
return new GsonBuilder().setPrettyPrinting().create().toJson(this);
}
or apache commons lang reflection way
Well actually you will need to return something like this because toString has to return a string
public String toString() {
return "Name :" + this.name + "whatever :" + this.whatever + "";
}
and you actually do something wrong in the constructer you set the variable the user set to the name while you need to do the opposite.
What you shouldn't do
n = this.name
What you should do
this.name = n
Hopes this helps thanks
we can even write like this by creating a new String object in the class and assigning it what ever we want in constructor and return that in toString method which is overridden
public class Student{
int id;
String name;
String address;
String details;
Student(int id, String name, String address){
this.id=id;
this.name=name;
this.address=address;
this.details=id+" "+name+" "+address;
}
//overriding the toString() method
public String toString(){
return details;
}
public static void main(String args[]){
Student s1=new Student(100,"Joe","success");
Student s2=new Student(50,"Jeff","fail");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Nice and concise way is to use Lombok annotations. It has #ToString annotation, which will generate an implementation of the toString() method. By default, it will print your class name, along with each field, in order, separated by commas.
You can easily customize your output by passing parameters to annotation, e.g.:
#ToString(of = {"name", "lastName"})
Which is equivalent of pure Java:
public String toString() {
return "Person(name=" + this.name + ", lastName=" + this.experienceInYears + ")";
}
If you're just using toString() for debugging a DTO, you can generate human readable output automatically with something like the following:
import com.fasterxml.jackson.databind.ObjectMapper;
...
public String toString() {
try { return new ObjectMapper().writeValueAsString(this); }
catch (Exception e) { return "{ObjectMapper failed}"; }
}
However, this isn't appropriate for production deployments if the DTO may contain PII (which shouldn't be captured in logs).
Always have easy way: Right Click > Generate > toString() > select template that you want.
if you are use using notepad:
then
public String toString(){
return ""; ---now here you can use variables which you have created for your class
}
if you are using eclipse IDE then
press
-alt +shift +s
-click on override toString method here you will get options to select what type of variables you want to select.
But then in the toString() method you aren't actually returning a String, are you?
You'll have to return a String for this method to work.
public String toString() {
return "Name : " + this.name + " Height : " + this.height + " BirthDay : " + this.bday;
}

Hibernate retuns object not list [duplicate]

Sounds a little stupid, but I need help on my toString() method and it is very irking.
I tried looking up online because the toString is the one where it is screwing up and "not finding Kid constructor #2" even though it is there and I would even do something else and it doesn't work.
Ok that was a lot so here is my code:
import java.util.*;
class Kid {
String name;
double height;
GregorianCalendar bDay;
public Kid () {
this.name = "HEAD";
this.height = 1;
this.bDay = new GregorianCalendar(1111,1,1);
}
public Kid (String n, double h, String date) {
// method that toString() can't find somehow
StringTokenizer st = new StringTokenizer(date, "/", true);
n = this.name;
h = this.height;
}
public String toString() {
return Kid(this.name, this.height, this.bDay);
}
} //end class
Ok So my toString above (I know, my third parameter is off, should be a String) is off. If I hardcode a value in for the third thing it goes haywire and says it can't find this (up above). So how can I get the date and break it up?
Class calling this is below
class Driver {
public static void main (String[] args) {
Kid kid1 = new Kid("Lexie", 2.6, "11/5/2009");
System.out.println(kid1.toString());
} //end main method
} //end class
I tried researching multiple constructors and it really didn't help.
I tried researching toString() methods, and tried using previous toString() methods logic that I created previous but this is brand new so it never worked.
Help?
The toString is supposed to return a String.
public String toString() {
return "Name: '" + this.name + "', Height: '" + this.height + "', Birthday: '" + this.bDay + "'";
}
I suggest you make use of your IDE's features to generate the toString method. Don't hand-code it.
For instance, Eclipse can do so if you simply right-click on the source code and select Source > Generate toString
Java toString() method
If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the string representation of the object.
If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.
Advantage of Java toString() method
By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code.
Output without toString() method
class Student{
int id;
String name;
String address;
Student(int id, String name, String address){
this.id=id;
this.name=name;
this.address=address;
}
public static void main(String args[]){
Student s1=new Student(100,”Joe”,”success”);
Student s2=new Student(50,”Jeff”,”fail”);
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:Student#2kaa9dc
Student#4bbc148
You can see in the above example #1. printing s1 and s2 prints the Hashcode values of the objects but I want to print the values of these objects. Since java compiler internally calls toString() method, overriding this method will return the specified values. Let's understand it with the example given below:
Example#2
Output with overriding toString() method
class Student{
int id;
String name;
String address;
Student(int id, String name, String address){
this.id=id;
this.name=name;
this.address=address;
}
//overriding the toString() method
public String toString(){
return id+" "+name+" "+address;
}
public static void main(String args[]){
Student s1=new Student(100,”Joe”,”success”);
Student s2=new Student(50,”Jeff”,”fail”);
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:100 Joe success
50 Jeff fail
Note that toString() mostly is related to the concept of polymorphism in Java.
In, Eclipse, try to click on toString() and right click on it.Then, click on Open Declaration and see where the Superclass toString() comes from.
As others explained, the toString is not the place to be instantiating your class. Instead, the toString method is intended to build a string representing the value of an instance of your class, reporting on at least the most important fields of data stored in that object. In most cases, toString is used for debugging and logging, not for your business logic (except some historical methods, like Integer.toString()).
To generate text representing the value of an object for display to a user, add another method. People often name the method something like getDisplayName. For example, DayOfWeek::getDisplayName and Month::getDisplayName.
StringJoiner
As of Java 8 and later, the most modern way to implement toString would use the StringJoiner class. As the doc says:
StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.
Use like this:
#Override
public String toString ()
{
return new StringJoiner( // In Java 8 and later, StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.
" | " , // Delimiter
Person.class.getSimpleName() + "[ " , // Prefix
" ]" // Suffix
)
.add( "name=" + name ) // Append
.add( "phone=" + phone ) // Append
.toString(); // Convert entire sequence to a single `String` object.
}
Person[ name=Alice | phone=555.867.5309 ]
record
Java 16 brings a new way to briefly define a class where the main purpose is to communicate data transparently and immutably: record.
You define a record by merely listing the type and name of each member field. The compiler implicitly creates the constructor, getters, equals & hashCode, and toString.
Default implementation of toString
The default implementation of toString includes each and every member field.
public Kid ( String name , double height , LocalDate birthDate ) {}
Instantiate like any other object.
Kid alice = new Kid( "Alice" , 6.1d , LocalDate.of( 2019 , Month.April , 23 ) ) ;
String output = alice.toString() ;
You may choose to override the default implementation with your own. Overrides are usually not needed given the purpose of a record as a simple data-carrier.
You can creating new object in the toString().
use
return "Name = " + this.name +" height= " + this.height;
instead of
return Kid(this.name, this.height, this.bDay);
You may change the return string as required. There are other ways to store date instead calander.
You can't call a constructor as if it was a normal method, you can only call it with new to create a new object:
Kid newKid = new Kid(this.name, this.height, this.bDay);
But constructing a new object from your toString() method is not what you want to be doing.
Following code is a sample. Question based on the same, instead of using IDE based conversion, is there a faster way to implement so that in future the changes occur, we do not need to modify the values over and over again?
#Override
public String toString() {
return "ContractDTO{" +
"contractId='" + contractId + '\'' +
", contractTemplateId='" + contractTemplateId + '\'' +
'}';
}
If you're interested in Unit-Tests, then you can declare a public "ToStringTemplate", and then you can unit test your toString. Even if you don't unit-test it, I think its "cleaner" and uses String.format.
public class Kid {
public static final String ToStringTemplate = "KidName='%1s', Height='%2s', GregCalendar='%3s'";
private String kidName;
private double height;
private GregorianCalendar gregCalendar;
public String getKidName() {
return kidName;
}
public void setKidName(String kidName) {
this.kidName = kidName;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public GregorianCalendar getGregCalendar() {
return gregCalendar;
}
public void setGregCalendar(GregorianCalendar gregCalendar) {
this.gregCalendar = gregCalendar;
}
public String toString() {
return String.format(ToStringTemplate, this.getKidName(), this.getHeight(), this.getGregCalendar());
}
}
Now you can unit test by create the Kid, setting the properties, and doing your own string.format on the ToStringTemplate and comparing.
making ToStringTemplate static-final means "ONE VERSION" of the truth, rather than having a "copy" of the template in the unit-test.
The best way in my opinion is using google gson library:
#Override
public String toString() {
return new GsonBuilder().setPrettyPrinting().create().toJson(this);
}
or apache commons lang reflection way
Well actually you will need to return something like this because toString has to return a string
public String toString() {
return "Name :" + this.name + "whatever :" + this.whatever + "";
}
and you actually do something wrong in the constructer you set the variable the user set to the name while you need to do the opposite.
What you shouldn't do
n = this.name
What you should do
this.name = n
Hopes this helps thanks
we can even write like this by creating a new String object in the class and assigning it what ever we want in constructor and return that in toString method which is overridden
public class Student{
int id;
String name;
String address;
String details;
Student(int id, String name, String address){
this.id=id;
this.name=name;
this.address=address;
this.details=id+" "+name+" "+address;
}
//overriding the toString() method
public String toString(){
return details;
}
public static void main(String args[]){
Student s1=new Student(100,"Joe","success");
Student s2=new Student(50,"Jeff","fail");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Nice and concise way is to use Lombok annotations. It has #ToString annotation, which will generate an implementation of the toString() method. By default, it will print your class name, along with each field, in order, separated by commas.
You can easily customize your output by passing parameters to annotation, e.g.:
#ToString(of = {"name", "lastName"})
Which is equivalent of pure Java:
public String toString() {
return "Person(name=" + this.name + ", lastName=" + this.experienceInYears + ")";
}
If you're just using toString() for debugging a DTO, you can generate human readable output automatically with something like the following:
import com.fasterxml.jackson.databind.ObjectMapper;
...
public String toString() {
try { return new ObjectMapper().writeValueAsString(this); }
catch (Exception e) { return "{ObjectMapper failed}"; }
}
However, this isn't appropriate for production deployments if the DTO may contain PII (which shouldn't be captured in logs).
Always have easy way: Right Click > Generate > toString() > select template that you want.
if you are use using notepad:
then
public String toString(){
return ""; ---now here you can use variables which you have created for your class
}
if you are using eclipse IDE then
press
-alt +shift +s
-click on override toString method here you will get options to select what type of variables you want to select.
But then in the toString() method you aren't actually returning a String, are you?
You'll have to return a String for this method to work.
public String toString() {
return "Name : " + this.name + " Height : " + this.height + " BirthDay : " + this.bday;
}

How do I add an item from a class to an ArrayList?

I know the question seems weird, but I'll try to explain it the best that I can. I am doing an Amusement Park Project where you have methods for the tickets, merchandise, etc. I made a Ticket class with the methods, but now I'm in the AmusementPark class trying to create a method of taking the date from that class and putting it into a new ArrayList. Maybe my code will help explain it.
First, here is my Ticket class......
import java.text.DecimalFormat;
public class Ticket {
private long number;
private String category;
private String holder;
private String date;
private double price;
private boolean purchased;
Ticket(long num, String cat, String h, String dt, double pr, boolean pch){
this.number= num;
this.category= cat;
this.holder= h;
this.date= dt;
this.price= pr;
this.purchased= pch;
}
long getNumber(){
return number;
}
String getCategory(){
return category;
}
String getHolder(){
return holder;
}
String getDate(){
return date;
}
boolean getPurchased(){
return purchased;
}
double getPrice(){
return price;
}
void setPrice(double pr){
price= pr;
}
void setChangePurchased(boolean newStatus){
purchased= newStatus;
}
#Override
public String toString(){
DecimalFormat dm= new DecimalFormat("#.##");
String disp;
disp = "Number: " + getNumber() + "\nCategory: " + getCategory() + "\nTicket Holder Name: " + getHolder() + "\nDate: " + getDate()
+ "\nPrice: " + dm.format(getPrice()) + "\nPuchased Completed?: " + purchased;
return disp;
}
}
Here is some of the Pseudo Code explaining what I am trying to do with the next class I'm about to post.
Create an ArrayList from the Ticket class.
//The ticket class has the following constructors....
// (Ticket number of type long, category of type String, Ticket holder of type String, Date of admission, purchase price of type double, variable named "purchased" whether the ticket has been paid for of type boolean)
//One of the variables of type class is tickets in which the ticket class is made into an ArrayList.
//The next task is to get tickets for dates where they are available, which is done by searching tickets where the purchase is not completed.
Create a public ArrayList<Date> method called getTicketDates(){
Create a variable called theDateArray which is a new ArrayList<Date>;
For(starting at the first position of the list, go through the the entire list incrementing by one){
if (boolean purchased of the Ticket ArrayList is false)**{
Add the date of the object from the Ticket ArrayList to theDateArray ArrayList.}** //This stores the dates of all tickets not yet purchased into the new ArrayList.
}
Return theDateArray;
}
//The next task is to search through theDateArray for only select dates and post the available tickets for that date as an integer.
Create a method which displays the number of tickets for a specified date by going through theDateArray (Date date) {
For(starting at the first position of theDateArray, go through the entire list and look for tickets that have a particular date){
if (the date== entered date){
Include the ticket as one of the tickets available for that date.
}
}
Return the total number of tickets available for that date as a type integer.
}
Okay, now here is my AmusementPark class. Note It is not finished. I'm just trying to get this one part done....
import java.util.ArrayList;
import java.util.Date;
public class AmusementPark {
private ArrayList<Ticket> tickets;
private ArrayList<Merchandise> merchandise;
private String name;
AmusementPark(String name){
this.name=name;
this.tickets = new ArrayList<Ticket>();
this.merchandise= new ArrayList<Merchandise>();
}
String getName(){
return name;
}
public ArrayList<String> getTicketDates(){
ArrayList<String> theDateArray= new ArrayList<>();
int i;
String date = Ticket.getDate(); //This is not working. See Reason Below.
for (i=0; i<tickets.size(); i++){
if(tickets.get(i).getPurchased()== false){
theDateArray.add(date);
}
}return theDateArray;
}
}
Okay, so now what happens when I try to call the method of getDate() from the Ticket class, it's not allowing me to use it for the reason that I cannot make a static reference to a non-static method. However, when I try to make the method static, it messes up the other class by saying I cannot make a static reference to a non-static field.
An ArrayList of the Ticket class has already been made. I need it to scroll through that list, get the ones where the boolean is false, and add the date to the next ArrayList.
Does this at all make sense?
Any ideas that would be better?
Let's take your method.
public ArrayList<String> getTicketDates(){
ArrayList<String> theDateArray= new ArrayList<>();
int i;
String date = Ticket.getDate(); //This is not working. See Reason Below.
for (i=0; i<tickets.size(); i++){
if(tickets.get(i).getPurchased()== false){
theDateArray.add(date);
}
}
return theDateArray;
}
Notice the problem on the Ticket.getDate() that you try to do whithout an instance, so a static call. But what you explain, you want the date for the Ticket of the list tickets. Good, you are iterating it after but are pushing this strange value date coming from a "static method".
You problem is that the instance holding the date you want is in the list. You are using it to see if it is purchased or not. So call the method on those instance to get the value :
for (i=0; i<tickets.size(); i++){
if(tickets.get(i).getPurchased()== false){
theDateArray.add(tickets.get(i).getDate());
}
}
But better :
Ticket ticket;
for (i=0; i<tickets.size(); i++){
ticket = tickets.get(i);
if(ticket.getPurchased()== false){
theDateArray.add(ticket.getDate());
}
}
If I understand it correctly what is required here is to extract dates for not purchased tickets into separate dates array. And you already got it correctly in your pseudocode, you just need to follow it more strictly during implementation:
public ArrayList<String> getTicketDates() {
ArrayList<String> theDateArray = new ArrayList<>();
// iterate over all tickets
for ( Ticket ticket : tickets ) {
// if ticket not purchased
if ( ! ticket.getPurchased() ) {
// add ticket's date into array
theDateArray.add( ticket.getDate() );
}
}
return theDateArray;
}
DON'T MAKE STATIC REFERENCE !Instead of writing a what's code answer let's focus on the workaround of problem.
Whenver you will set values to instance variables of TICKET Class it will refer to a particular object (new ticket()) to access its values if you make variables of class staticValues will be stored when class is loaded and not when object is created but arraylist items need to have
Object of ticket Class.
A simple approach should be
ASSIGN THE VALUES TO VARIABLES WHEN EVER YOU MAKE AN OBJECT OF TICKET CLASS BY BY PASSING VALUES IN ITS CONSTRUCTOR AND THEN
ADD THOSE OBJECTS TO ARRAYLISTITEMS
ticket class
public class Ticket {
private long number;
private String category;
private String holder;
private String date;
private double price;
private boolean purchased;
Ticket(long num, String cat, String h, String dt, double pr, boolean pch){
this.number= num;
this.category= cat;
this.holder= h;
this.date= dt;
this.price= pr;
this.purchased= pch;
}
make a new object and pass values
Ticket t1=new Ticket(3,"yourstring","yourstring",yourDouble,true/false);
add items in arrayliSt:
List<Tickets> tList=new ArrayList();
tList.add(t1);
tList.add(t2);
//and so on
now retrive values from arralylist
Ticket t=tlist.get(0);
t.cat;
t.whatevrbe thevalue be

How to return HashMap object fields

I currently have the following HashMap in a Holiday class.
Holiday Class:
HashMap <String, Location> holidays = new HashMap<String, Location>();
This creates an instance of the Location class, to allow more fields to be shown.
Location class:
public class Location {
private String locationName;
private String locationDesc;
private double price;
private int quantity;
public Location(String locationName, String locationDesc, double price) {
this.locationName = locationName;
this.locationDesc = locationDesc;
this.price = price;
quantity = 0;
}
public String toString() {
return (locationName + " | " + "£" + price);
}
public double getPrice() { return price; }
public String getLocationName() { return locationName; }
public String getLocationDesc() { return locationDesc; }
public int getQuantity() { return quantity; }
}
In my GUI class I just use the .get HashMap method, this will return the toString.
e.g
GUI class
private Holiday holiday;
...
return holiday.holidays.get(--HashMap key here--);
this will return the toString, which is locationName and price.
However. I'm wanting to also print out the HashMap elsewhere, but with returning different fields. such as returning the Description and quantity as well as locationName and price. How would i go about doing this? Or how do i return the individual fields from the Location class which is an instance of in the HashMap.
MANAGED TO DO THIS. But need help with the following below
Second EDIT:
I have a set quantity method in my Location class, to set the amount of bookings for each holiday. However when using;
for (Location location : holiday.holidays.values()) {
location.setQuantity(Integer.parseInt(textFieldQuantity.getText()));
}
This changes all of the holidays to the same quantity when setting each location with a different quantity. How do i fix this?
The result of holidays.get(key) should be an object of type Location. If you print the object directly, like in System.out.println(holidays.get(key)) it will print the result of toString() as you say. But since you already have the object and access to its fields, you can print exactly what you want.
Something like this should work:
Location location = holidays.get(key);
System.out.println(location.getlocationDesc() + " | " + location.getQuantity());
Regarding your second question:
If you just need to print all values stored in your map, I think it would be cleaner and faster to iterate directly on the map values:
for (Location location : holiday.holidays.values()) {
System.out.println(location.getlocationDesc() + " | " + location.getQuantity());
}
Third question:
Note that your code does not set the quantity for only one location. It goes through all locations setting each quantity to the same value, defined by textFieldQuantity.getText().
If you want to modify a specific location, you need to retrieve it from the map using get():
Location location = holiday.holidays.get(key);
location.setQuantity(Integer.parseInt(textFieldQuantity.getText()));
Why not try something like:
private Location location = holiday.holidays.get(--HashMap key here--);
// Create a string with the variables
And then return the string.
this will return the toString, which is locationName and price
No. It will return an instance of Location. So all you have to do is
Location location = holiday.holidays.get("some key");
double price = location.getPrice();
String locationName = location.getLocationName();
Note that
you shouldn't use public fields. So it should be instead location.getHolidays().get("some key"). Or even better, to encapsulate the Map and respect the "don't talk to strangers" rule, location.getHoliday("some key").
Your getter should be named getLocationName() and not getlocationName() to respect the JavaBean conventions. Or even better, since this method is part of a Location class, the location prefix is redundant, and you should thus simply name it getName() (and getDescription() for the description)

How to override toString() properly in Java?

Sounds a little stupid, but I need help on my toString() method and it is very irking.
I tried looking up online because the toString is the one where it is screwing up and "not finding Kid constructor #2" even though it is there and I would even do something else and it doesn't work.
Ok that was a lot so here is my code:
import java.util.*;
class Kid {
String name;
double height;
GregorianCalendar bDay;
public Kid () {
this.name = "HEAD";
this.height = 1;
this.bDay = new GregorianCalendar(1111,1,1);
}
public Kid (String n, double h, String date) {
// method that toString() can't find somehow
StringTokenizer st = new StringTokenizer(date, "/", true);
n = this.name;
h = this.height;
}
public String toString() {
return Kid(this.name, this.height, this.bDay);
}
} //end class
Ok So my toString above (I know, my third parameter is off, should be a String) is off. If I hardcode a value in for the third thing it goes haywire and says it can't find this (up above). So how can I get the date and break it up?
Class calling this is below
class Driver {
public static void main (String[] args) {
Kid kid1 = new Kid("Lexie", 2.6, "11/5/2009");
System.out.println(kid1.toString());
} //end main method
} //end class
I tried researching multiple constructors and it really didn't help.
I tried researching toString() methods, and tried using previous toString() methods logic that I created previous but this is brand new so it never worked.
Help?
The toString is supposed to return a String.
public String toString() {
return "Name: '" + this.name + "', Height: '" + this.height + "', Birthday: '" + this.bDay + "'";
}
I suggest you make use of your IDE's features to generate the toString method. Don't hand-code it.
For instance, Eclipse can do so if you simply right-click on the source code and select Source > Generate toString
Java toString() method
If you want to represent any object as a string, toString() method comes into existence.
The toString() method returns the string representation of the object.
If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc. depends on your implementation.
Advantage of Java toString() method
By overriding the toString() method of the Object class, we can return values of the object, so we don't need to write much code.
Output without toString() method
class Student{
int id;
String name;
String address;
Student(int id, String name, String address){
this.id=id;
this.name=name;
this.address=address;
}
public static void main(String args[]){
Student s1=new Student(100,”Joe”,”success”);
Student s2=new Student(50,”Jeff”,”fail”);
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:Student#2kaa9dc
Student#4bbc148
You can see in the above example #1. printing s1 and s2 prints the Hashcode values of the objects but I want to print the values of these objects. Since java compiler internally calls toString() method, overriding this method will return the specified values. Let's understand it with the example given below:
Example#2
Output with overriding toString() method
class Student{
int id;
String name;
String address;
Student(int id, String name, String address){
this.id=id;
this.name=name;
this.address=address;
}
//overriding the toString() method
public String toString(){
return id+" "+name+" "+address;
}
public static void main(String args[]){
Student s1=new Student(100,”Joe”,”success”);
Student s2=new Student(50,”Jeff”,”fail”);
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:100 Joe success
50 Jeff fail
Note that toString() mostly is related to the concept of polymorphism in Java.
In, Eclipse, try to click on toString() and right click on it.Then, click on Open Declaration and see where the Superclass toString() comes from.
As others explained, the toString is not the place to be instantiating your class. Instead, the toString method is intended to build a string representing the value of an instance of your class, reporting on at least the most important fields of data stored in that object. In most cases, toString is used for debugging and logging, not for your business logic (except some historical methods, like Integer.toString()).
To generate text representing the value of an object for display to a user, add another method. People often name the method something like getDisplayName. For example, DayOfWeek::getDisplayName and Month::getDisplayName.
StringJoiner
As of Java 8 and later, the most modern way to implement toString would use the StringJoiner class. As the doc says:
StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.
Use like this:
#Override
public String toString ()
{
return new StringJoiner( // In Java 8 and later, StringJoiner is used to construct a sequence of characters separated by a delimiter and optionally starting with a supplied prefix and ending with a supplied suffix.
" | " , // Delimiter
Person.class.getSimpleName() + "[ " , // Prefix
" ]" // Suffix
)
.add( "name=" + name ) // Append
.add( "phone=" + phone ) // Append
.toString(); // Convert entire sequence to a single `String` object.
}
Person[ name=Alice | phone=555.867.5309 ]
record
Java 16 brings a new way to briefly define a class where the main purpose is to communicate data transparently and immutably: record.
You define a record by merely listing the type and name of each member field. The compiler implicitly creates the constructor, getters, equals & hashCode, and toString.
Default implementation of toString
The default implementation of toString includes each and every member field.
public Kid ( String name , double height , LocalDate birthDate ) {}
Instantiate like any other object.
Kid alice = new Kid( "Alice" , 6.1d , LocalDate.of( 2019 , Month.April , 23 ) ) ;
String output = alice.toString() ;
You may choose to override the default implementation with your own. Overrides are usually not needed given the purpose of a record as a simple data-carrier.
You can creating new object in the toString().
use
return "Name = " + this.name +" height= " + this.height;
instead of
return Kid(this.name, this.height, this.bDay);
You may change the return string as required. There are other ways to store date instead calander.
You can't call a constructor as if it was a normal method, you can only call it with new to create a new object:
Kid newKid = new Kid(this.name, this.height, this.bDay);
But constructing a new object from your toString() method is not what you want to be doing.
Following code is a sample. Question based on the same, instead of using IDE based conversion, is there a faster way to implement so that in future the changes occur, we do not need to modify the values over and over again?
#Override
public String toString() {
return "ContractDTO{" +
"contractId='" + contractId + '\'' +
", contractTemplateId='" + contractTemplateId + '\'' +
'}';
}
If you're interested in Unit-Tests, then you can declare a public "ToStringTemplate", and then you can unit test your toString. Even if you don't unit-test it, I think its "cleaner" and uses String.format.
public class Kid {
public static final String ToStringTemplate = "KidName='%1s', Height='%2s', GregCalendar='%3s'";
private String kidName;
private double height;
private GregorianCalendar gregCalendar;
public String getKidName() {
return kidName;
}
public void setKidName(String kidName) {
this.kidName = kidName;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public GregorianCalendar getGregCalendar() {
return gregCalendar;
}
public void setGregCalendar(GregorianCalendar gregCalendar) {
this.gregCalendar = gregCalendar;
}
public String toString() {
return String.format(ToStringTemplate, this.getKidName(), this.getHeight(), this.getGregCalendar());
}
}
Now you can unit test by create the Kid, setting the properties, and doing your own string.format on the ToStringTemplate and comparing.
making ToStringTemplate static-final means "ONE VERSION" of the truth, rather than having a "copy" of the template in the unit-test.
The best way in my opinion is using google gson library:
#Override
public String toString() {
return new GsonBuilder().setPrettyPrinting().create().toJson(this);
}
or apache commons lang reflection way
Well actually you will need to return something like this because toString has to return a string
public String toString() {
return "Name :" + this.name + "whatever :" + this.whatever + "";
}
and you actually do something wrong in the constructer you set the variable the user set to the name while you need to do the opposite.
What you shouldn't do
n = this.name
What you should do
this.name = n
Hopes this helps thanks
we can even write like this by creating a new String object in the class and assigning it what ever we want in constructor and return that in toString method which is overridden
public class Student{
int id;
String name;
String address;
String details;
Student(int id, String name, String address){
this.id=id;
this.name=name;
this.address=address;
this.details=id+" "+name+" "+address;
}
//overriding the toString() method
public String toString(){
return details;
}
public static void main(String args[]){
Student s1=new Student(100,"Joe","success");
Student s2=new Student(50,"Jeff","fail");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Nice and concise way is to use Lombok annotations. It has #ToString annotation, which will generate an implementation of the toString() method. By default, it will print your class name, along with each field, in order, separated by commas.
You can easily customize your output by passing parameters to annotation, e.g.:
#ToString(of = {"name", "lastName"})
Which is equivalent of pure Java:
public String toString() {
return "Person(name=" + this.name + ", lastName=" + this.experienceInYears + ")";
}
If you're just using toString() for debugging a DTO, you can generate human readable output automatically with something like the following:
import com.fasterxml.jackson.databind.ObjectMapper;
...
public String toString() {
try { return new ObjectMapper().writeValueAsString(this); }
catch (Exception e) { return "{ObjectMapper failed}"; }
}
However, this isn't appropriate for production deployments if the DTO may contain PII (which shouldn't be captured in logs).
Always have easy way: Right Click > Generate > toString() > select template that you want.
if you are use using notepad:
then
public String toString(){
return ""; ---now here you can use variables which you have created for your class
}
if you are using eclipse IDE then
press
-alt +shift +s
-click on override toString method here you will get options to select what type of variables you want to select.
But then in the toString() method you aren't actually returning a String, are you?
You'll have to return a String for this method to work.
public String toString() {
return "Name : " + this.name + " Height : " + this.height + " BirthDay : " + this.bday;
}

Categories

Resources