Printing reference to an object [duplicate] - java

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
I am a newbie in java. Say, I have a class Individual. I want to print
Individual ind = new Individual();
System.out.println(ind);
Above code gives output like this:
Individual#1922221
What is the significance of this?
Is it some kind of unique id
for that object?
Can I customize this? I mean write a function of
my own which will give output when I print?
If so, how can I do
this?

If you want to print meaningful content of any object, you have to implement your own toString() method, which will override the parent(Object) class's toString() method. By default all the classes(Whatever you create) extends Object class.
Sample Code:
public class Individual {
private String name;
private String city;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Name of Individual :").append(this.getName())
.append("\nCity :").append(this.getCity());
return builder.toString();
}
public static void main(String[] args) {
Individual individual = new Individual();
individual.setName("Crucified Soul");
individual.setCity("City of Crucified Soul");
System.out.println(individual);
}
}
Output:
Name of Individual :Crucified Soul
City :City of Crucified Soul
If you have bigger class with many variables, you can use XStream to implement your toString() method. XStream will print your object meaningful in XML format. Even you can parse them back to equivalent object. Hope this would help you.

This is the result of default toString() method - the classname + hashcode. This can be override by overriding toString().
Some reference here: http://www.javapractices.com/topic/TopicAction.do?Id=55

Since it hasn't been explained yet, overriding the toString() method simply means that you create a toString() method of your own in your class. By putting your own version of toString() in your class, you make it so that java will use your toString() method rather than the default. Because the original toString() method returns a string, however, your toString() method must also return a string. Your Individual class would look something like this:
public class Individual{
//any other code in the class
public String toString(){
return "your string";
}
}
Then, when you called your System.out.print(ind); it would print out your string.

I think you want to overwrite Individual toString. See http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#toString()

Related

How to resolve a need for a static method in an interface?

I have 2 classes: Rectangle and Circle.
Each of them implements the interface "JSONSerializable" with the methods "import" and "export".
In order to differentiate between the two classes the interface has a third method "getType" which simply returns "rectangle" or "circle" depending on the class.
This works fine and i get a JSON String which looks something like this:
{
type:rectangle,
points:[{1,2},{2,2},{2,1},{1,1}]
}
When i read the String again i need to decide which import method to call, depending on the type. What I did now is this:
public enum JSONType{
Rectangle(Rectangle.getStaticType()),
Circle(Circle.getStaticType());
private final String type;
JSONType(String type){
this.type = type;
}
public String getType(){
return type;
}
}
This works, i can then read the JSON-String and compare against all String types in my enum. However, I need to declare two methods (getType() and static getStaticType()) for every child objects, where both return the same String:
public static String getStaticType(){
return "rectangle";
}
public String getType(){
return Rectangle.getStaticType();
}
Is there any way around that? I think the answere is no, but I've never before had a situation like this. I'm happy for any design advice :)

Succinct way to print using multiple getter methods - Java

I have quite a few getter methods in a class and I need to print the return of those getters (Just one and not all of them at once). I need to be able to do this with one print() method but I am not sure how to do this. Is there a way to dynamically call another method and then print the return of that method?
Here are a couple of getter methods:
public String getEmail()
{
return this.studentEmail;
}
public Integer getAge()
{
return this.studentAge;
}
Here is what I am wanting to do:
public void print(???)
{
System.out.println(theGetterMethod);
}
I know that I can create a bunch of print methods but I need to be able to do this with one method.
As asked by the OP:
"I think you were correct with your first comment and it can be an answer."
From:
"You can tackle it by using Sytem.out.println ("E-mail: " + ...getEmail(), " Age: " + ...getAge()); If you want to go overkill you can use reflection."
Meaning instead of having a seperate print() method you will instead be invoking the right accessor for the value you want to print.
This is one of reasons why you use accessors in the place, as now you are exposing the fields without any risk of having the user change them.
You can still change on underlying Objects apart from String as it is immutable.
You can call methods dynamically based on their name by using reflection.
In this example I assume that each Getter follows a pattern and just pass over the property name that I want to print out:
import java.lang.reflect.Method;
public class Student {
private String studentEmail = "MyEmail";
private Integer studentAge = 20;
public String getEmail() {
return this.studentEmail;
}
public Integer getAge() {
return this.studentAge;
}
// Prints out a property based on the name
public void print(String property) throws Exception {
for (Method method : this.getClass().getMethods())
if (method.getName().equals("get" + property))
System.out.println(method.invoke(this, null));
}
// Prints out all properties with a getter
public void print() throws Exception {
for (Method method : this.getClass().getMethods())
if (method.getName().startsWith("get"))
System.out.println(method.invoke(this, null));
}
}
And than call the method like that:
Student s = new Student();
s.print("Email");
s.print("Age");

How can I support println in a class?

What does my own made class need to support in order for println() to print it? For example, I have:
public class A {
...
}
What methods should class A have to make this code work? Maybe something like this:
public static void main() {
A a = new A();
System.out.println(a);
}
I have a guess that the toString() method must be overloaded. Am I right? Is this enough?
You can print any Object using System.out.println(Object). This overloaded version of println will print out toString representation of your object. If you want to customize what will be printed out, you must override the Object#toString() method, for example:
public class A {
private String foo;
#Override
public String toString() {
// When you print out instance of A, value of its foo
// field will be printed out
return foo;
}
}
If you don't override the Object#toString() method, default implementation from Object class will be used, which has this form (class name and the hexidecimal representation of the instance hash code):
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
Bonus: if you need to create toString() implementation from multiple fields, there are tools to make it easier. For instance ToStringBuilder from Commons Lang. Or some Java IDEs like IntelliJ IDEA even offer to generate toString for you based on the class' fields.
You need to provide an override of toString() method for this:
public class A {
#Override
public String toString() {
return "A";
}
}
The method returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object.
You need implement toString() method. Everything you return from it will be printed.

Java arraylist indexof

Here is my class animals.java:
public class animals {
String Name, ID;
static ArrayList<animals> animalData = new ArrayList<animals>();
public animals(){}
public animals(String name, String id){
super();
this.Name = name;
this.ID = id;
}
public void addAnimal(String name, String id){
animalData.add(new animals(name, id));
}
public int search(String name){
return this.animalData.indexOf(name);
}
}
When I add an animal name with an id it works normally, but when I use search method I saw only -1. Maybe I try override method equals or indexof in this class? help me for this
Thank you and sorry for my bad english..
You are adding instances of animals to the list. You are searching for the instance by name. Since animalData does not contain any instances of String, indexOf() will never return an index.
If you want to access an instance of animals by the name, you should use a Map<String,animals>.
Map<String,animals> animalMap = new HashMap<String,animals>();
animalMap.put("Mat", new animals("Mat", "id");
animals animal = animalMap.get("Mat");
The proper use of indexOf() is to pass in an instance that is equal to an instance already in the collection. As others have pointed out, this will require you to define equals() to define what makes two instances equal. You should also override hashcode() when you override equals() because there is an assumed correlation.
Note: The convention is to use CapitalCase for class names. Also, the class name should not be plural. You will have many instances of Animal, you may later make a class that is a collection of Aniamals, but that should not be the name of the main class.
Yes, you need to override equals() and hashcode() methods when you use objects in collections and perform lookup based on object.
indexOf() returns object because it just returns object at that perticular index. But, when you do object based lookup, if equals() and hashCode() are not overridden, equals() may fail and you get unpredictable results.
You need to define an "equals" method
You're looking for a String...
You'd better use a HashMap I think...
But yeah you have to change your structure(which isn't very efficient)
Here is the code I would use:
public class animals {
String Name, ID;
static Map<String, animals> animalData = new HashMap<String, animals>();
public animals(){}
public animals(String name, String id){
super();
this.Name = name;
this.ID = id;
}
public static void addAnimal(String name, String id){
animalData.add(new animals(name, id));
}
// Returns null if no registered animal has this name.
public animals search(String name){
return this.animalData.get(name);
}
}
This way, you make the search method much faster (O(1)), you don't need to override the equals method anymore.
Note that if animalData is static, you should consider to make addAnimal() static as well since it's sort of a 'setter' for aniamalData.

can constructors actually return Strings?

I have a class called ArionFileExtractor in a .java file of the same name.
public class ArionFileExtractor {
public String ArionFileExtractor (String fName, String startText, String endText) {
String afExtract = "";
// Extract string from fName into afExtract in code I won't show here
return afExtract;
}
However, when I try to invoke ArionFileExtractor in another .java file, as follows:
String afe = ArionFileExtractor("gibberish.txt", "foo", "/foo");
NetBeans informs me that there are incompatible types and that java.lang.String is required. But I coded ArionFileExtractor to return the standard string type, which is java.lang.string.
I am wondering, can my ArionFileExtractor constructor legally return a String?
I very much appreciate any tips or pointers on what I'm doing wrong here.
Constructors create objects, they don't return data.
Your method, ArionFileExtractor(), is not a constructor. Consutructors do not have return types, and look like this:
public ArionFileExtractor (String fName, String startText, String endText) {
//...
}
Note the lack of a return type.
A constructor can only return an instance of object that it constructed - otherwise you have no reference against which to hang on to the object you just created! If you want to make a "utility" call, consider a static method:
public class ArionFileExtractor {
public static String getFileContents(String fName, String startText, String endText) {
String afExtract = "";
// Extract string from fName into afExtract in code I won't show here
return afExtract;
}
}
Which can be invoked using
ArionFileExtractor.getFileContents(...)
As much as this is surprising, the code you made has a default no argument constructor. ArionFileExtractor is a method that returns a String. I was quite surprised when I first saw code that did this, as it is certainly an accident (as in your case).
You could call you method (just to show this is the case) with:
String afe = new ArionFileExtractor().ArionFileExtractor("gibberish.txt", "foo", "/foo");
What it really sounds like you are trying to get at is a static method, not a class at all.
public class ArionFileExtractor() {
public static String extract(String fName, String startText, String endText) {
String afExtract = "";
// Extract string from fName into afExtract in code I won't show here
return afExtract;
}
}
which you would call with:
String afe = ArionFileExtractor.extract("gibberish.txt", "foo", "/foo");
Constructor is not a regular method. It always returns instance of the class that it belongs to. In your example ArionFileExtractor. There is no way to return any other instance.
Notice that you can't specify return type for constructor explicitly nor use return keyword (illegal in this context).
Java compiler treats ArionFileExtractor as an instance method,
String afe = new ArionFileExtractor().ArionFileExtractor("gibberish.txt", "foo", "/foo");
Constructor can only return instance of its class. It cannot return String.
For instance if you have class SampleClass, constructor can return only object of class SampleClass.
No it should not be able to legally return a String. I'm not sure why Netbeans didn't simply barf at you when you tried to. Maybe it tried to compile it as some sort of static method. Constructors do not generally have return types in code, because when they are compiled they are assigned to return an instance of the class they are constructing.
The easiest (though not necessarily best) way to adapt your code would be to have an empty constructor and turn the current constructor into a static method like this:
public class ArionFileExtractor {
private ArionFileExtractor() {}
public static String ExtractFile(String fName, String startText, String endText) {
String afExtract = "";
// Extract string from fName into afExtract in code I won't show here
return afExtract;
}
}
The private constructor makes it so that ArionFileExtractor can only be used statically and cannot be instantiated. Then when you use it you simply do this:
String afe = ArionFileExtractor.ExtractFile("gibberish.txt", "foo", "/foo");
Be warned, using static classes is sometimes considered bad form - depending on the situation. So it might be worth while to try and come up with a different way to do this.
No.
A constructor does not really return anything. Instead it builds the object in question.
It looks like you want a utility method here:
public class Whatever {
public static String doStuff(String s) {
return s;
}
}
Yes.Only String class constructor can return string objects out of it ;).
This basically means that the constructor creates the object of the class you are calling.
You need to FIRST create the object (using the constructor) and THEN do stuff with it.
Java has very few smart shortcuts. I

Categories