How to print List's object elements in Java? [duplicate] - java

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
I have something like the following:
List<Interval> intervals = new LinkedList<Interval>();
intervals.add(new Interval(1));
intervals.add(new Interval(2));
How can I print the List intervals? I attempted System.out.println(intervals), but it simply returns [Interval#...].
Thank you

The issue is not in printing the List but in printing the Interval.
Implement Interval.toString() method.

System.out.println(intervals) will call .toString() method of the object you are trying to print, which is List.
In order to print every object you have to override the toString() method for Interval or print specific value.
for (Inteval interval : intervals) { System.out.println(interval.getValue());}
or if you override the toString() method for Interval
for (Inteval interval : intervals) { System.out.println(interval);}
You can override the toString() as follows:
public class Interval {
public int value;
public String val;
#Override
public String toString() {
return "Value string: " + val + " value int: " + value;
}
}

Related

why am i getting a NullPointerException Java [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
So im writing a Java programming, I have 2 classes, and a class test that uses these 2 classes. running eclipseIDE, it keeps telling me i have a NullPointerException at the "s+=c.getName() + " " +... "
this is a method in Student.
public String getCourses()
{
String s = "";
for(Course c: this.courses)
{
s+=c.getName() + " " + c.getID() + " " + c.getScore(this.id);
s+="\n";
}
return s;
}
it calls this method that is in the Course class.
public String getID()
{
return this.id;
}
i tried only doing getName(); it had no issue, however once i added getID() it became an issue. getName is the same type of code, it returns the "name" of the object as a string.
name and id is "initialized" via a constructor
Stacktrace:
Exception in thread "main" java.lang.NullPointerException
at hw6.Student.getCourses(Student.java:47)
at hw6.CourseStudent_test.main(CourseStudent_test.java:100)
this is the getScore method
public double getScore(String id)
{
int i = 0;
for(; i < this.students.length;i++)
{
if(this.students[i].getID() == id )
{
break;
}
}
return this.scores[i];
}
If the exception is occurring where your stacktrace + question says it is, then one of the elements in courses must be null.
Reasoning:
If the exception was thrown inside one of the Course method calls, then the stacktrace would show that method as the top stack frame.
If one of those 3 calls returned null, you wouldn't get an NPE. You would just get "null" in the resulting concatenation; see String concatenation with Null.
Found the issue, Because of the "For each " loop, when it gets to an Null object, it tries to run the getter methods, however each time it returns null, as there is no "value" for each variable within that object, so i just added a if condition to check if the object is "null"

Implemented hashCode() but retainAll() still isn't working as expected [duplicate]

This question already has answers here:
Java Hashset.contains() produces mysterious result
(3 answers)
Closed 4 years ago.
I have a doctor object and each object has a unique attribute "docMobile"(primary key). I made two different LinkedHashSets (doctorsByLoc & doctorsByAvail) of doctors. Now when i do a
doctorsByLoc.retainAll(doctorsByAvail)
on the two sets it deletes all the elements even though both have the same doctors.
I have implemented hashCode() Method in my doctor class. I also printed the sets individually to check in the sets have same elements.
public class Doctor{
String docName;
long docMobile;
String docLocation;
int docDays;
#Override
public int hashCode() {
return Long.hashCode(docMobile);
}
}
Then somewhere in a servlet something like this happens
public static void main(String[] args){
Set<Doctor> doctorsByLoc = new LinkedHashSet<>();
Set<Doctor> doctorsByAvail = new LinkedHashSet<>();
doctorsByLoc.add(d1);
doctorsByLoc.add(d2);
doctorsByLoc.add(d3);
doctorsByAvail.add(d1);
doctorsByAvail.add(d2);
doctorsByAvail.add(d3);
System.out.println("Before retain All "+doctorsByLoc.size());
for(Doctor d:doctorsByLoc){
System.out.println(d.getdocName());
}
doctorsByLoc.retainAll(doctorsByAvail);
System.out.println("After retain All"+doctorsByLoc.size());
for(Doctor d:doctorsByLoc){
System.out.println(d.getdocName());
}
}
Actual output:
Before retain All 3
d1's name
d2's name
d3's name
After retain All 0
How can i fix my hashcode method so that the doctors remain.
I have tried printing the hashcode before returning it and I got pairs of similar hashcode as output.
You did not override equals correctly. You should be overriding it as follows:
#Override
public boolean equals (Object other) // Not "Doctor other"
{
// implementation here
}

My arraylist is displaying object address not object contents [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 4 years ago.
arraylist displays object address not actual object , program usesinheritance where salesEmployee is the super class and salesAgent and salesPerson are the subclasses.
import java.util.Scanner;
import java.util.ArrayList;
public class tester {
public static void main(String[]args ) {
ArrayList <salesEmployee> listemps= new ArrayList <salesEmployee>();
Scanner user_input= new Scanner(System.in);
salesPerson emp1 = new salesPerson();
emp1.setName("Frank Long");
emp1.setppsNumber(65783);
System.out.println("Enter total value of sales earned by Frank Long");
double valeSale;
valeSale=user_input.nextDouble();
emp1.setvalSale(valeSale);
emp1.getCommission();
listemps.add(emp1);
for ( int j=0; j<listemps.size(); j++ )
System.out.println("element " + j + ": " + listemps.get(j) );
}
}
This is my salesPerson class
public class salesPerson extends salesEmployee{
public salesPerson() {
}
public salesPerson(String name, int ppsNumber, double valSale, double commission) {
super(name, ppsNumber,valSale,commission);
}
public void getCommission() {
commission=valSale*0.15;
}
public String toString2() {
return toString1()+"value of sales"+getvalSale()+"commission:"+commission;
}
}
I'll make it more elegant later for now I am just trying to get it to work
Updated: Based on the comments to my answer, there is a different issue at play. Here's what was added in the comments:
Enter total value of sales earned by Frank Long 22.00
Exception in thread "main" java.lang.StackOverflowError at
salesPerson.toString(salesPerson.java:21) at
salesPerson.toString(salesPerson.java:21) at
salesPerson.toString(salesPerson.java:21) at
salesPerson.toString(salesPerson.java:21) – lucylio 5 mins ago
Is what comes up – lucylio 5 mins
In order for something reasonable to be displayed, you need to implement toString method in your class. You do have toString1 and toString2, but seemingly, no toString. (You haven't posted the code for salesEmployee class - but most likely it also doesn't have toString implementation).
In absence of toString, default Object.toString is called, which displays the address of the object.
Implement toString - and you'll see your results.
UPDATE: As the error you indicated doesn't correspond to the code, I'll go on a whim and suggest that, probably your toString2 method is actually toString and your toString1 method is actually a toString defined in your parent class, i.e. salesEmployee.java. In this case, instead of calling toString() from inside your toString method, use super.toString() instead:
public class salesPerson extends salesEmployee {
...
public String toString2() {
return super.toString()+"value of sales"+getvalSale()+"commission:"+commission;
}
}

Array prints memory address despite Override [duplicate]

This question already has answers here:
I am getting the memory address from an arraylist, need info
(2 answers)
Closed 8 years ago.
Now, I want it to only print what it says, without the memory address as well. How would I achieve that?
public Telefonnummer[] getTelenummer() {
Telefonnummer[] tnummer = new Telefonnummer[nummerarray.size()];
nummerarray.toArray(tnummer);
System.out.println(Arrays.toString(tnummer) );
return tnummer;
}
Is the constructor and:
private static void kundSök() {
System.out.println("...? ");
String namn = keyboard.nextLine();
if (kunderna.containsKey(namn)) {
for (String k : kunderna.keySet()) {
Kund kund = kunderna.get(k);
System.out.println(kund);
System.out.println(kund.getTelenummer());
After i have added a person to the ArrayList etc it gives me an output of:
Sam wasdfgn
[123456: efdg]
[LTelefonnummer;#28d93b30
The last part, memory address bit, is the part I want to get rid of.
Yet again, how do i achieve that?
Edit: I tried to Override, but it did not do anything at all. Could there be another problem?
The default behaviour for toString is to print the type name (as L followed by the type name), followed by # and the hexString of the hashCode (which by default is the memory address for the object).
To change this, override the toString method for your Telefonnummer class.
public class Telefonnummer {
private String nummer;
...
#Override public String toString() {
return "Dial " + nummer + " for a good time";
}
}
Guava library has Joiner which can be used for that. See https://code.google.com/p/guava-libraries/wiki/StringsExplained
String str = Joiner.on(",").join(list);
You also have to have working toString function on class for elements of the list

Print Array of Objects in BlueJ [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
For an assignment, I was asked to work on calling a class and creating an array objects, which i did here;
public void DVDArrayObjects() {
//creates variables
int i;
DVDClass[] dvdArray = new DVDClass[5];
//reference to DVDClass
for (i = 0; i < 2; i ++) {
//create new instance of calling the class
dvdArray[i] = new DVDClass();
//create new instance of getting the info
dvdArray[i].getDVDInfo();
//display
//System.out.println(dvdArray[i]);
}
}
Creating the array of objects works fine, but displaying doesn't. it shows the memory allocation when i run it. I'm really stuck as to how to get it to display.
** EDIT **
When i use System.out.println(dvdArray[i].getDVDInfo()); the error void types not allowed in here shows up
** END OF EDIT **
Any help at all would be greatly appreciated.
Print the DVD info (assuming that it returns a string).
System.out.println(dvdArray[i].getDVDInfo());
If it doesn't return a string, you need to override the toString() method on the class DVDInfo like this.
#Override
public String toString()
{
return "Film Name\t: " + filmName +
"\nFilm Director\t: " + filmDirector +
"\nRun Time\t: " + runTime +
"\nLead Actor\t: " + leadActor;
}
Hope this helps.
You need to override the toString() method.
public class DVDCLass {
#Override
public String toString(){
return // whatever you want the output to be
}
}
Override toString() method in your DVDClass class
do like below
class DVDClass{
public String toString(){
return // whatever you want the output to be
}
}

Categories