This question already has answers here:
How to use the toString method in Java?
(13 answers)
Closed 8 years ago.
I've been given the following array
tests[] b = new tests[50];
So, there are some null elements in this array and I don't want to print those in my array.
for(int i = 0; i < b.length; i++){
if(b[i] != null){
System.out.println(b[i]);
}
}
So, this prints out '#251970e2' but I need to be able to print out each valid elements contents which should be like 'batman', 'joker', 'batgirl'
Sorry if this has been answered previously, I had a look but haven't had much luck :(
You need to override toString method in your class because it is going to give you clear information about the object in readable format that you can understand.
The merit about overriding toString:
Help the programmer for logging and debugging of Java program
Since toString is defined in java.lang.Object and does not give valuable information, so it is
good practice to override it for subclasses.
#override
public String toString(){
// I assume name is the only field in class test
return name ;
}
Override toString method in your Tests class ..
class Tests{
..... your code
#Override
public String toString(){
... return the value
}
}
You need to override the toString() method in your tests class.
For further discussion, see How to use the toString method in Java?
Related
i know this is very trivial, but for some reason i'm having a little trouble. i'm trying to write a method that has a book object from an array list calling the method that compares it to another book in the same list. I think i got the gist of it but i'm just not understanding how to compare them. i think it's supposed to look something like this.
public Boolean isShorter(Book otherBook)
{
if(otherBook.getLength() < ???????.getLength() )
return true;
else
return false;
}
use "this" keyword to refer to the current object (the caller of the method).
like this:
otherBook.getLength() < this.getLength()
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
I am wondering if I can use for each loop to iterate through the object of a class. for instance, I created an object honda of type car. I append all the state of the car such as model, price, color, etc. to it. I want to print all the instance of the car. I don't want to use the print statement to print each instance . what is the best way to do it? Thanks.
Below is my java code
package classandobjects;
public class MainClass {
public static void main(String[] args) {
Classes friend1 = new Classes();
friend1.name="yusuf";
friend1.age=27;
friend1.country="Nigeria";
friend1.department="EE";
friend1.gender="male";
Classes friend2 = new Classes();
friend1.name="mathew";
friend1.age=30;
friend1.country="Nigeria";
friend1.department="EE";
friend1.gender="male";
FavPlayers player = new FavPlayers();
player.pname="J.Terry";
player.position="C.Back";
player.gaols=38;
player.awards="25-awards";
FavPlayers player1 = new FavPlayers();
player1.pname="F.Lampard";
player.position="Midfield";
player.gaols=50;
player.awards="10-awards";
Car model = new Car();
model.modelName="Honda Civic";
model.color="Ash-color";
model.Doors="4-doors";
model.price=900000;
System.out.println("below is my friend information");
System.out.println(friend1.name);
System.out.println(friend1.age);
}
}
You had better override a toString method in the Car class and simply print it like:
System.out.println(model);
Indeed, you needn't print each instance variable separately. Your toString may have the following view:
public #Override String toString() {
return modelName + " [" + color + ... + "]"; // also consider StringBuilder
}
If you came from languages where an object is an associative array (e.g. JavaScript) and asked how to print an instance using a foreach loop in Java, then the answer is that Java doesn't allow it (it is possible by reflection though) and you cannot iterate over object variables through a foreach.
I don't want to use the print statement to print each instance
Well, you're going to have to build up a string and print it somewhere.
what is the best way to do it?
If I understand correctly, you want to print an object?
Then implement a toString() method.
public class Classes {
// other code
public String toString() {
// change how you want
return this.name + ", " + this.age;
}
}
Then you can do
System.out.println(friend1);
If you want to print a list of objects, then you need a list to loop over. You could use reflection to get a list of object fields and values, but that seems unnecessary.
This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 8 years ago.
In working on an Euler problem as a new Java programmer, I have encountered something peculiar related to printing an array.
I do not understand why this is happening - the individual values appear to be correct, when printed individually, but the toString() is clearly creating a string which is not what I expect.
I would have expected either a compile error, or the array to be put into a concatenated list. Neither of these happened.
Note: I am not interested in "how to print an array?" but rather understanding why the toString() does NOT print the array. There are plenty of resources online available to find how to do so.
public class example {
public static void main(String[] args) {
/* Setup a string/int array converion*/
int i=0;
String nums = "123456";
char[] splitNums = nums.toCharArray();
int[] ints = new int[nums.length()];
for (char c : splitNums) {
ints[i++] = Character.digit(c,10);
}
//Print using the string/char[]
System.out.println(nums);
System.out.println(splitNums);
//Values are clearly there
for (int j : ints){
System.out.println(j);
}
//What is toString() doing?
System.out.println(ints.toString());
}
}
Output:
123456
123456
1
2
3
4
5
6
[I#4b71bbc9
The output [I#4b71bbc9 that you see is the output of the method Object.toString(). Arrays are objects in Java, but they don't have their own implementation of a toString() method - so java.lang.Object's version is called, which prints this kind of output (see the docs).
To print an array, do this instead:
System.out.println(Arrays.toString(ints));
toString() are implicitly called when you are printing an object. Since ints is an array (treated as object) and not a primitive.
When your ints are placed within a println statement, the toString() method inherited from Class Object are invoked printing what you saw on your screen.
So why does it inherit from Class Object?
This is because every class in Java implicitly extends from Class Object.
To print an array with a println statement, you can do this:
System.out.println(Arrays.toString(arrayName));
It will print out the formatted array nicely for you:
Example:
[0, 1, 2, 3, 4]
About toString()
The toString() method 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.
-From the API of toString-
So in general a toString() method makes a printed object meaningful and textually understandable of what the object represents. However there are a few exception when printing object such as String objects and char array. The reason which is self-explanatory (String already in String)
This question already has answers here:
Difference between Equals/equals and == operator?
(11 answers)
Closed 8 years ago.
I am studying some example code that enrol customer into a service, and the method below checks if the customer has that type of service. I assume that if we want to compare to objects, i.e. service, we need to use equals() method.
However the code below (in customer class) works perfectly fine, but it did't work after I changed == to equals.() Can someone help to explain why it behave like this? Is it because under some circumstances we need check equality using ==? Many thanks!
boolean hasService(Service sd) { //Service is a class that has int, String and ArrayList as variable
boolean hasService = false;
for (int i=0; i<.length; ++i) { //
//doesn't work if change to ((serviceAvailable[i] ).equals(pd)), why?
if (serviceAvailable[i]==sd) //serviceAvailable is an Array stores different services
hasService = true;
}
return hasService;
}
The class Service is as below:
class Serivce {
private String name;
private int price;
private ArrayList <Customers> customersErolled;
//geters and setters methods
boolean equals (Serive a){
if (this.paperName.equals(a.paperName)&&a.semester==this.semester&& a.year==this.year&&a.studentsEnrolled.equals(this.studentsEnrolled) ){
return true;
}else{
return false;
}
The equality operator == will compare the object references, while equals will depend on the implementation of equals on the object that you are comparing. By default this will compare the hash of the object (which is unique for each object in the jvm that your code runs in at that moment).
For a propper equals you need to override the equals method in Service and compare the instance variables there one by one (or whathever kind of equality you want / need).
This question already has answers here:
Implementing toString on Java enums
(4 answers)
Closed 8 years ago.
I'm new to Java and I'm learning the language fundamentals.
Can someone explain to me how the toString method is called when there is no function call to it? I think it has something to do with the actual enumerator words on the second line such as:
KALAMATA("Kalamata"), LIGURIO("Ligurio") ...
The whole purpose for this enum class is so the ENUM values don't print to screen in all upper case characters.
Can someone please explain me how toString method is used in this class? Like when is it called? How is it called?
public enum OliveName {
KALAMATA("Kalamata"),LIGURIO("Ligurio"),PICHOLINE("Picholine"),GOLDEN("Golden");
private String nameAsString;
//for enum classes, the constructor must be private
private OliveName(String nameAsString) {
this.nameAsString = nameAsString;
}
#Override
public String toString() {
return this.nameAsString;
}
}
Pretty much like any object.
OliveName oliveName = OliveName.KALAMATA;
System.out.println(oliveName.toString());
or
System.out.println(oliveName);