How to print all the elements from a ArrayList? - java

I'm trying to print all the element I have added to my arraylist, but it only prints the adress and not the string.
Can someone help me or give out some tips? I've been searching all afternoon

You need to override Autuer's toString method to return its contents in String format

You can also, use a foreach to do it ;)
for(Auteur a: auteurs){
System.out.print(a.getName() + " - " + a.getNumber());
}

itr.next() returns object of Auteur rather than String. To print the name you need to type cast it with Auteur and then print it if you have a print method for the class Auteur.
Auteur aut = (Auteur) itr.next();
System.out.println(aut.printMethod());

Try defining the toString() method in your Auter class as follows:
public String toString() {
return this.getName() + " - " + this.getNumber());
}
and your code will do what you wish. System.out.println calls the argument's toString() method and prints that out to the Output console.

Every object in Java inherits
public String toString();
from java.lang.Object
in your Auteur class you need to write some code similar to the following:
....
....
#Override
public String toString() {
return "Name: "+this.name;
}

What you see is called the default toString of an object. It is an amalgamation of the FQCN (fully qualified class name) of the class it belongs to and the hashCode of the object.
Quoting from the JavaDoc of toString:
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())
We can override toString to give a more human readable output. Take a look at the below two classes, with and without toString. Try to execute the main method and compare the output of the two print statements.
class Person {
private String name;
#Override
public String toString() {
return "Person [name=" + this.name + "]";
}
}
class Address {
private String town;
}
public class Test {
public static void main(String... args) {
Person person = new Person();
Address address = new Address();
System.out.println("Person is : " + person);
System.out.println("Address is : " + address);
}
}

Related

Why is it common practice to override the method toString() in java to print the instance variables of the class?

As I've been learning and even some IDEs have it embeded in it, to override the toString() method to print out all instance variables of the class.
The original toString() defined in object.java is defined as follows:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
And it's common practice to override it as:
public String toString() {
return "className{" +"var1="+var1+", var2="+var2+'}';
}
Why don't we keep the original functionality of the toString() method and create a new method (with a different name) with this functionality?
We could. But how will other classes, that know absolutely nothing about your subclasses with your myNewToString method, know how to print a string that textually represents, in a concise but informative way, arbitrary subclasses?
The toString method was designed to be overridden to do that. Yes, it does have default behavior but it's not very useful. Its authors wanted you to override it. Overriding it to return what's commonly practiced is more useful, but you don't have to do that. A toString method for an EmailAddress class can return
public String toString() {
return "EmailAddress{localPart = " + localPart + ", domainName = " + domainName + "}";
}
but it's usually more useful to return something like
public String toString() {
return localPart + "#" + domainName;
}
The reason to override toString() is that toString() is called implicit by the compiler every time an object which is not of type String, is added to a string.
So if you have
MyObject o=new MyObject();
C="Hello " + o;
Then the compiler will call o.toString() in order to get a string it can concat to "Hello "
And I should note that it checks if o is null before calling toString() on o. And if o is null, it just generate the string "null"
Opinion: The toString() method should in general and in most cases only be used for debugging (Print/Log) and not as part of the normal program flow.

How to write the contents of my array in a text file?

I have an array which has objects of people in a football team. It holds information such as their first name, second name and address. When i use the code shown below the text file contains values like this: member#29086037
The code is shown below:
try
{
PrintWriter pr = new PrintWriter ("memberDetails.txt");
for (int i = 0; i < collection.length; i++)
{
pr.println(collection[i]);
}
pr.close();
} catch (FileNotFoundException ex)
{
System.out.println(ex.getMessage());
System.out.println("in" + System.getProperty("user.dir"));
System.exit(1);
}
What am I doing wrong?
When you see that malarky with the numbers and class name like that, it means you haven't overriden your toString() method, so it defaults to Object.toString().
So, override the public String toString() method on your member class.
When you do pr.println(collection[i]); as you didn't override it, you print Object::toString which represents the object in this way by default:
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())
To print each field, use properties of the object, for example:
collection[i].getName();
collection[i].getAddress();
Other option, is to override toString() method of member.
You have to provide the path to the file correctly. I would suggest creating a file object and then pass it to Printwriter. This way you can also make sure if File exist before assigning it to printwriter.
As others have pointed out, assuming you have a class that models the players, you should provide a toString() implementation in the class. For example:
public class Player {
private String firstName;
private String lastName;
private String address;
...
#Override
public String toString() {
return String.format("Name: %s, %s. Address: %s", lastName, firstName, address);
}
}
After that's been done, it becomes trivial to write the player information into a file. Using an utility library such as Google's Guava, the solution simplifies into a one-liner:
Files.write(Joiner.on(StandardSystemProperty.LINE_SEPARATOR.value())
.join(collection),
new File("memberDetails.txt"),
Charsets.UTF_8);

arraylist returning random numbers and not proper data

so I've got an arraylist
private static ArrayList<Job> teamNoOne = new ArrayList<Job>();
Of type Job, which has
public class Job {
//public long time;
public int teamNo;
public String regNo;
public String gridRef;
}
Then I'm getting data from a textField
Job job = new Job();
job.gridRef = tfGridRef.getText();
This all works, printed it to system etc.
When I add it to the arraylist, and print it out using the following code:
teamNoOne.add(job);
System.out.println(teamNoOne.get(0));
I just get this: Job#1c79dfc
cannot for the life of me figure out why,
Cheers
When a object is printed using sysout, its toString method is called. If toString method is not overridden in the class, then its default implementation will be used. Default implementation of an object toString method prints the class name and the unsigned hexadecimal representation of the hash code of the object separated by # symbol.
You need to override the toString method in your Job class in order to print the object in a pretty way. Most of the IDEs provide a way to auto- generate the toString method. Here is one generated through eclipse:
#Override
public String toString() {
return "Job [teamNo=" + teamNo + ", regNo=" + regNo + ", gridRef="
+ gridRef + "]";
}

Class method called by only presenting object name

I have the following piece of code
public class DriverTester {
public static void main(...){
// test empty constructor
Person p1 = new Person();
System.out.println("p1: " + p1);
}
}
public class Person {
private String name;
// Empty constructor
public Person () {
}
// getter avoided for simplicity
public String toString() {
return "Mr.or Ms. "+this.name;
}
}
It compiles, runs succesfully and shows "Mr or Mrs null". So, that would b e the result of calling the toString method.
I don't understand the syntax in of the print line method. How is it that simply the name of the object p1 runs a given method. How does it know which method to run? Shouldn't the syntax be
System.out.println("p1: " + p1.getName());
or
System.out.println("p1: " + p1.toString());
Thanks for any clarification
When concatenating strings, such as in this line:
System.out.println("p1: " + p1);
Java will call the toString() method to convert any object to a String for concatenation. Java ensures that this method exists on all objects, because it's defined on the Object class, which every class implicitly inherits from.
Additionally, if a null is concatenated, then Java will convert that into the String "null".
The Java Language Specification, section 5.1.11, covers "String Conversion":
If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l).
Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but
if the result of invoking the toString method is null, then the
string "null" is used instead.
PrintStream used by System.out.println uses String.valueOf
649 public void print(Object obj) {
650 write(String.valueOf(obj));
651 }
which in turn uses the Object's toString method provided the Object itself is not null, otherwise the literal "null" is returned.
2837 public static String valueOf(Object obj) {
2838 return (obj == null) ? "null" : obj.toString();
2839 }

Get Object from reference Id

is it possible to get an object from his reference id?
i get a list of String containing the reference id of an object like:
com.test.test.business.model.Gamma#20
how to get the object from this reference id?
it's only a string and it isn't castable to the object itself
What you see is called the default toString of an object. It is an amalgamation of the FQCN (fully qualified class name) of the class it belongs to and the hashCode of the object.
Quoting from the JavaDoc of toString:
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())
In short, you can't get an object using this reference id.
We can override toString to give a more human readable output. Take a look at the below two classes, with and without toString. Try to execute the main method and compare the output of the two print statements.
class Person {
private String name;
#Override
public String toString() {
return "Person [name=" + this.name + "]";
}
}
class Address {
private String town;
}
public class Test {
public static void main(String... args) {
Person person = new Person();
Address address = new Address();
System.out.println("Person is : " + person);
System.out.println("Address is : " + address);
}
}
However, if you are really looking for a way to persist objects and resurrect them at a later stage, you should read up on Serialization.

Categories