concept two object in category java

appears as: two objects
Get Programming with Java MEAP V04 livebook

This is an excerpt from Manning's book Get Programming with Java MEAP V04 livebook.

In this example, I used two of the methods from the Object class: toString() and getClass().  Other helpful methods include clone() and equals(Object o). Since Strings are stored as objects in Java, we cannot use the == to compare two String objects.  So, if we want to compare these two objects, the code must use the .equals(Object o) method from the Object class to make the comparison.  If we tried to use ==, the program would try to compare the reference value of each object, which contains the location in memory for each object.  This is only the same when two objects are pointing to the exact same location, in other words, they are aliases of each other. Also, in this example, I have explicitly imported the java.lang.Object class, but it is not required. The java.lang package is imported by default into every Java program.

Now let’s talk about comparing objects.  When we create an object variable, the variable stores a reference value to the location of the object data in memory.  When we use the keyword new to create a new instance of a class, the memory location is stored in the variable. Even if these two objects have the exact same values, the reference values will be different.  So, if we compare these two objects to test for equality using the symbol ==, it will return false.  Figures 17.1 and 17.2 show the difference between comparing two primitive data types and two objects.

Figure 17.2 shows what happens when comparing two objects
Figure 17.1 shows what happens when comparing two primitive data values

In the previous section, I demonstrated one way to check if two objects are equal. There are times when we not only need to check if they are equal, we might also need to know which comes first based on our business requirements. This type of comparison is usually needed to help sort a list of objects. 

In my example, the business requirements might require that the application has the ability to sort the Person objects by last name.  Lucky for us, Java provides a Comparable interface that can be used to define the process for comparing two objects.  We start by implementing the Comparable interface and then provide an overridden method for the abstract method, compareTo(Object o).  Code listing 17.4 shows an example of how to use the Comparable interface. To save space, I have only added two Person objects and sorted them by last name. I’ve also added an overridden toString method to return the person name.

sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage