It's exactly as the title says, I am trying to pass an object into a method, so that I can compare strings. The object doesn't convert properly, showing up as "MediaItem#9a2", and I know I have to use override but I'm not quite sure how to do this.
public class MediaItem {
private String title;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public MediaItem(String t)
{
setTitle(t);
}
public MediaItem()
{
}
public boolean equals(Object obj)
{
String temptitle = getTitle();
temptitle = temptitle.toLowerCase();
temptitle = temptitle.trim();
// System.out.println(temptitle);
String tempobj = obj.toString();
System.out.println(tempobj);
tempobj=tempobj.toLowerCase();
tempobj= tempobj.trim();
System.out.println(tempobj);
if (temptitle.equals(tempobj))
{
System.out.println("this");
return true;
}
else{
return false;
}
}
#Override
public String toString()
{
return obj.title;
}
}
There's a bad attempt at overriding at the bottom of the code. Also, not sure why all the colour has disappeared from the code.
Edit: Ok maybe I should add some more explanation: The task is to compare the obj sent in and the title of the current object. If they match, I return true. If not, I return false. The only thing I am allowed to change is the stuff within the equals(object obj) method. I can also add override. That's it. Is there an easier way to do this than what I was trying to do?
To get human readable representation of the object you should override toString() method, that's correct. However you should do it like that:
public String toString() {
return title; // No obj!
}
// or like that
public String toString() {
return "MyClass{title=" + title + "}";
}
What you are doing wrong is comparing objects. It's a complex topic but there is a quick example:
#Override
public boolean equals(Object o) {
return o != null
&& getClass() == o.getClass()
&& Objects.equals(title.toLowerCase().trim(),
o.title.toLowerCase().trim()); // for each field
}
public String toString()
{
return title;
}
is sufficient you could also use return this.title; however the this is implicit as there are no other title defined in the method
Overriding the toString() method is when you wanna do some custom external serialization for the toString() rather than the usual object hashed code. For comparing obj using equal(), you need to custom the equals method depends on your needs, like fields comparision, hashed comparison, etc.
Can anybody explain to me the concept of the toString() method, defined in the Object class? How is it used, and what is its purpose?
From the Object.toString docs:
Returns a string representation of the
object. In general, the toString
method returns a string that
"textually represents" this object.
The result should be a concise but
informative representation that is
easy for a person to read. It is
recommended that all subclasses
override this method.
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())
Example:
String[] mystr ={"a","b","c"};
System.out.println("mystr.toString: " + mystr.toString());
output:- mystr.toString: [Ljava.lang.String;#13aaa14a
Use of the String.toString:
Whenever you require to explore the constructor called value in the String form, you can simply use String.toString...
for an example...
package pack1;
import java.util.*;
class Bank {
String n;
String add;
int an;
int bal;
int dep;
public Bank(String n, String add, int an, int bal) {
this.add = add;
this.bal = bal;
this.an = an;
this.n = n;
}
public String toString() {
return "Name of the customer.:" + this.n + ",, "
+ "Address of the customer.:" + this.add + ",, " + "A/c no..:"
+ this.an + ",, " + "Balance in A/c..:" + this.bal;
}
}
public class Demo2 {
public static void main(String[] args) {
List<Bank> l = new LinkedList<Bank>();
Bank b1 = new Bank("naseem1", "Darbhanga,bihar", 123, 1000);
Bank b2 = new Bank("naseem2", "patna,bihar", 124, 1500);
Bank b3 = new Bank("naseem3", "madhubani,bihar", 125, 1600);
Bank b4 = new Bank("naseem4", "samastipur,bihar", 126, 1700);
Bank b5 = new Bank("naseem5", "muzafferpur,bihar", 127, 1800);
l.add(b1);
l.add(b2);
l.add(b3);
l.add(b4);
l.add(b5);
Iterator<Bank> i = l.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
}
... copy this program into your Eclipse, and run it... you will get the ideas about String.toString...
The toString() method returns a textual representation of an object. A basic implementation is already included in java.lang.Object and so because all objects inherit from java.lang.Object it is guaranteed that every object in Java has this method.
Overriding the method is always a good idea, especially when it comes to debugging, because debuggers often show objects by the result of the toString() method. So use a meaningful implementation but use it for technical purposes. The application logic should use getters:
public class Contact {
private String firstName;
private String lastName;
public Contact (String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {return firstName;}
public String getLastName() {return lastName;}
public String getContact() {
return firstName + " " + lastName;
}
#Override
public String toString() {
return "["+getContact()+"]";
}
}
It may optionally have uses within the context of an application but far more often it is used for debugging purposes. For example, when you hit a breakpoint in an IDE, it's far easier to read a meaningful toString() of objects than it is to inspect their members.
There is no set requirement for what a toString() method should do. By convention, most often it will tell you the name of the class and the value of pertinent data members. More often than not, toString() methods are auto-generated in IDEs.
Relying on particular output from a toString() method or parsing it within a program is a bad idea. Whatever you do, don't go down that route.
toString() returns a string/textual representation of the object.
Commonly used for diagnostic purposes like debugging, logging etc., the toString() method is used to read meaningful details about the object.
It is automatically invoked when the object is passed to println, print, printf, String.format(), assert or the string concatenation operator.
The default implementation of toString() in class Object returns a string consisting of the class name of this object followed by # sign and the unsigned hexadecimal representation of the hash code of this object using the following logic,
getClass().getName() + "#" + Integer.toHexString(hashCode())
For example, the following
public final class Coordinates {
private final double x;
private final double y;
public Coordinates(double x, double y) {
this.x = x;
this.y = y;
}
public static void main(String[] args) {
Coordinates coordinates = new Coordinates(1, 2);
System.out.println("Bourne's current location - " + coordinates);
}
}
prints
Bourne's current location - Coordinates#addbf1 //concise, but not really useful to the reader
Now, overriding toString() in the Coordinates class as below,
#Override
public String toString() {
return "(" + x + ", " + y + ")";
}
results in
Bourne's current location - (1.0, 2.0) //concise and informative
The usefulness of overriding toString() becomes even more when the method is invoked on collections containing references to these objects. For example, the following
public static void main(String[] args) {
Coordinates bourneLocation = new Coordinates(90, 0);
Coordinates bondLocation = new Coordinates(45, 90);
Map<String, Coordinates> locations = new HashMap<String, Coordinates>();
locations.put("Jason Bourne", bourneLocation);
locations.put("James Bond", bondLocation);
System.out.println(locations);
}
prints
{James Bond=(45.0, 90.0), Jason Bourne=(90.0, 0.0)}
instead of this,
{James Bond=Coordinates#addbf1, Jason Bourne=Coordinates#42e816}
Few implementation pointers,
You should almost always override the toString() method. One of the cases where the override wouldn't be required is utility classes that group static utility methods, in the manner of java.util.Math. The case of override being not required is pretty intuitive; almost always you would know.
The string returned should be concise and informative, ideally self-explanatory.
At least, the fields used to establish equivalence between two different objects i.e. the fields used in the equals() method implementation should be spit out by the toString() method.
Provide accessors/getters for all of the instance fields that are contained in the string returned. For example, in the Coordinates class,
public double getX() {
return x;
}
public double getY() {
return y;
}
A comprehensive coverage of the toString() method is in Item 10 of the book, Effective Java™, Second Edition, By Josh Bloch.
Whenever you access an Object (not being a String) in a String context then the toString() is called under the covers by the compiler.
This is why
Map map = new HashMap();
System.out.println("map=" + map);
works, and by overriding the standard toString() from Object in your own classes, you can make your objects useful in String contexts too.
(and consider it a black box! Never, ever use the contents for anything else than presenting to a human)
Correctly overridden toString method can help in logging and debugging of Java.
Coding:
public class Test {
public static void main(String args[]) {
ArrayList<Student> a = new ArrayList<Student>();
a.add(new Student("Steve", 12, "Daniel"));
a.add(new Student("Sachin", 10, "Tendulkar"));
System.out.println(a);
display(a);
}
static void display(ArrayList<Student> stu) {
stu.add(new Student("Yuvi", 12, "Bhajji"));
System.out.println(stu);
}
}
Student.java:
public class Student {
public String name;
public int id;
public String email;
Student() {
}
Student(String name, int id, String email) {
this.name = name;
this.id = id;
this.email = email;
}
public String toString(){ //using these toString to avoid the output like this [com.steve.test.Student#6e1408, com.steve.test.Student#e53108]
return name+" "+id+" "+email;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email=email;
}
}
Output:
[Steve 12 Daniel, Sachin 10 Tendulkar]
[Steve 12 Daniel, Sachin 10 Tendulkar, Yuvi 12 Bhajji]
If you are not used toString() in Pojo(Student.java) class,you will get an output like [com.steve.test.Student#6e1408, com.steve.test.Student#e53108].To avoid these kind of issue we are using toString() method.
Apart from what cletus answered with regards to debugging, it is used whenever you output an object, like when you use
System.out.println(myObject);
or
System.out.println("text " + myObject);
The main purpose of toString is to generate a String representation of an object, means the return value is always a String. In most cases this simply is the object's class and package name, but on some cases like StringBuilder you will got actually a String-text.
/**
* This toString-Method works for every Class, where you want to display all the fields and its values
*/
public String toString() {
StringBuffer sb = new StringBuffer();
Field[] fields = getClass().getDeclaredFields(); //Get all fields incl. private ones
for (Field field : fields){
try {
field.setAccessible(true);
String key=field.getName();
String value;
try{
value = (String) field.get(this);
} catch (ClassCastException e){
value="";
}
sb.append(key).append(": ").append(value).append("\n");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return sb.toString();
}
If you learn Python first and then Java. I think it plays the same role as __str__() method in Python, it is a magic method like __dict__() and __init__() but to refer to a string representing the the object.
the toString() converts the specified object to a string value.
I have a common process with different progress values and step number, depending on the user.
To solve this I've made an interface :
public interface Progress {
int getTotalStepNumber();
int getIndex();
String getMessage();
#Override
String toString();
}
So a step process implementation is like this, litteraly, it is an enumeration of the steps for this process :
public enum ProgressImplementationOfProcessOne implements Progress {
STEP_ONE(1, "Step one message."),
STEP_TWO(2, "Step two message.");
// ... etc. with more steps
/**
* Number of steps for this process.
*/
private static final int STEPS = 2;
private int index;
private String message;
ProgressImplementationOfProcessOne(int index, String message) {
this.index = index;
this.message = message;
}
#Override
public int getTotalStepNumber() { return STEPS; }
#Override
public int getIndex() { return this.index; }
#Override
public String getMessage() { return this.message; }
#Override
public String toString() { return this.message; }
}
But then I thought it would be nice to find the corresponding step from implementation as well, with the method valueOf() of enumerations. So I added the following lines to my interface :
default Progress valueOf(String s) {
for (Progress progress : this.getValues()) {
if (progress.getMessage().equals(s)) {
return progress
}
}
return null;
}
default Progress valueOf(int i) {
for (Progress progress : this.getValues()) {
if (progress.getIndex() == this.getIndex()) {
return progress;
}
}
return null;
}
Since there is no getValues() method in the interface Progress I added the following method to it (thinking "the enum implementation will handle it natively").
default List<Progress> getValues() { return null; }
But I don't understand why I get this error for each ProgressImplementation :
This static method cannot hide the instance method from Progress..
I know I could do it by creating an additional class ProgressStep which replace an enum value, and replace enum by classes with attributes and so on, but since enum can handle multiple values I thought it could have been easier with it.
Simply rename the valueOf to something like valueOfEnum, as valueOf is already specified by java.lang.Enum.
public static <T extends Enum<T>> T valueOf(Class<T> enumType,
String name) {
T result = enumType.enumConstantDirectory().get(name);
if (result != null)
return result;
if (name == null)
throw new NullPointerException("Name is null");
throw new IllegalArgumentException(
"No enum constant " + enumType.getCanonicalName() + "." + name);
}
The comment on that method contains following section:
Note that for a particular enum type T, the implicitly declared public static T valueOf(String) method on that enum may be used instead of this method to mapfrom a name to the corresponding enum constant. All theconstants of an enum type can be obtained by calling the implicit public static T[] values() method of that type
Emphasis mine
As you can see, valueOf(String s) is already declared on every enum class which in turn is the reason, you can't have it in an interface on any enum
I have used enums in java in the past but for some reason I am getting a strange error right now. the Line of code that it is throwing the error is:
switch(ConfigProperties.valueOf(line[0].toLowerCase()){
...
}
I am getting a
java.lang.IllegalArgumentException: No enum const class
allautomator.ConfigProperties.language
in the example line is an array of Strings.
I am just really confused right now, I do not know what could possibly be wrong.
The enum constants are case sensitive, so make sure you're constants are indeed lower case. Also, I would suggest that you trim() the input as well to make sure no leading / trailing white-space sneak in there:
ConfigProperties.valueOf(line[0].toLowerCase().trim())
For reference, here is a working sample program containing your line:
enum ConfigProperties { prop1, prop2 }
class Test {
public static void main(String[] args) {
String[] line = { "prop1" };
switch (ConfigProperties.valueOf(line[0].toLowerCase())) {
case prop1: System.out.println("Property 1"); break;
case prop2: System.out.println("Property 2"); break;
}
}
}
Output:
Property 1
I am using a similar concept, but having a default value in case of fail
public enum SortType {
PRICE_ASC("price_asc"),
PRICE_DESC("price_desc"),
MODEL_ASC("model_asc"),
MODEL_DESC("model_desc");
private String name;
SortType(String name) {
this.name = name;
}
public String getName() {
return name;
}
static public SortType lookup(String id, SortType defaultValue) {
try {
return SortType.valueOf(id);
} catch (IllegalArgumentException ex) {
return defaultValue;
}
}
}
I want to override toString() for my enum, Color. However, I can't figure out how to get the value of an instance of Color inside the Color enum. Is there a way to do this in Java?
Example:
public enum Color {
RED,
GREEN,
BLUE,
...
public String toString() {
// return "R" for RED, "G", for GREEN, etc.
}
}
You can also switch on the type of this, for example:
public enum Foo {
A, B, C, D
;
#Override
public String toString() {
switch (this) {
case A: return "AYE";
case B: return "BEE";
case C: return "SEE";
case D: return "DEE";
default: throw new IllegalStateException();
}
}
}
public enum Color {
RED("R"),
GREEN("G"),
BLUE("B");
private final String str;
private Color(String s){
str = s;
}
#Override
public String toString() {
return str;
}
}
You can use constructors for Enums. I haven't tested the syntax, but this is the idea.
Enum.name() - who'd of thunk it?
However, in most cases it makes more sense to keep any extra information in an instance variable that is set int the constructor.
Use super and String.substring():
public enum Color
{
RED,
GREEN,
BLUE;
public String toString()
{
return "The color is " + super.toString().substring(0, 1);
}
}
Java does this for you by default, it returns the .name() in .toString(), you only need to override toString() if you want something DIFFERENT from the name. The interesting methods are .name() and .ordinal() and .valueOf().
To do what you want you would do
.toString(this.name().substring(1));
What you might want to do instead is add an attribute called abbreviation and add it to the constructor, add a getAbbreviation() and use that instead of .toString()
I've found something like this (not tested tho):
public enum Color {
RED{
public String toString() {
return "this is red";
}
},
GREEN{
public String toString() {
return "this is green";
}
},
...
}
Hope it helps a bit !