December 18, 2014
Hot Topics:

Objects and Collections

  • July 10, 2006
  • By Matt Weisfeld
  • Send Email »
  • More Articles »

Subtle Syntax

There is one more syntax note that I would like to point out. Java introduced an alternate form. The array brackets can be attached to the type itself as well as the array namem as can be seen in the following line of code.

int[] items = new int[5];

There is an interesting and subtle difference between the two types of declarations—they are not quite the same. Consider the following two lines of code.

int[] x;
int[] y;

The array brackets are attached to the type, not the name of the array.

The following line of code is equivalent.

int[] x, y;

Because the array brackets are attached to the type, you can create multiple integer arrays simply by providing the variable names.

You also can create arrays of arrays in this manner.

int[] x, y[];

Here, you have created an integer array of integer arrays called y[][].

It is in this same way that arrays of objects can be created, as can be seen in Listing 5. I have created a class called Employee, and the application creates two Employee arrays named fullTime and partTime.

public class ArrayLists {
   public static void main(String[] args) {
      Employee [] fullTime, partTime;
   }
}
class Employee {
}

Listing 5

Here is where you delve deeper into the relationships between objects and arrays.

Object-Oriented Arrays?

How do you know that the Java array is actually an object? Well, for one thing, the Java documentation tells you that it is. Java provides an Array class.

java.lang.reflect
Class Array

java.lang.Object
   java.lang.reflect.Array

Just like everything besides the primitives, the Array class inherits from the Object class.

How else can you determine that an array is really an object? All you need to do is to relate an array to the simple definition of an object, which is that all objects have attributes and behaviors.

Look at the code where you initialized the days of the week. Listing 6 shows how you can print out the entire array.

public class ArrayLists {
   public static void main(String[] args) {
      String days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
      for (int i = 0; i<7; i++) {
         System.out.println(days[i]);
      }
   }
}

Listing 6

When this code is executed, the following output is generated (the actual program output is in bold).

C:column24>"C:Program FilesJavajdk1.5.0_06binjava" ArrayLists
Sun
Mon
Tue
Wed
Thu
Fri
Sat
C:column24>

As you may have noticed already, the size of the array has been hard-coded in the loop. This is normally not coding practice. You actually can use some of the Array class's attributes to take care of this problem.

for (int i = 0; i < days.length; i++) {
   System.out.println(days[i]);
}

By using the length attribute of the Array class, you do not have to hard-code the value. This is important because any change in the size of the array will not necessitate a change to the code. For example, if you decide that you only want to include the weekdays in the array, all you have to do is change the array.

String days[] = { "Mon", "Tue", "Wed", "Thu", "Fri"};

The code for the loop remains the same.

One interesting issue here lies in the length attribute itself. Normally, in an object-oriented design, you cannot access attributes directly. Even if you don't consider length to be an attribute, it certainly is a value. And, one of the fundamental principles of object-oriented design is that you cannot access an attribute directly. To do so breaks the concept of encapsulation and data hiding. If you were designing an object-oriented class, you would create length as a private attribute and then create a method to return the value, say getLength( ). In another point of object-oriented design, you know that methods are indicated by the following parenthesis. In this case, length, does not have any trailing parenthesis.

More recently, Java now provides further syntax to loop through an array. Take a look at Listing 7. This syntax is similar to many of the language's foreach loop control.

public class ArrayLists {
   public static void main(String[] args) {
      String days[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
      for (String i: days) {
         System.out.println(i);
      }
   }
}

Listing 7

An Array object contains various items besides the actual contents of the array. You already have discussed the length attribute. An Array object also inherits all the methods from the Object class. These methods are the trait that truly distinguishes a class from a simple variable—the fact that objects have behaviors implemented by methods.

According to the Sun documentation, the members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array (length may be positive or zero)
  • The public method clone( ), which overrides the method of the same name in class Object and throws no checked exceptions
  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method
  • Every array implements the interfaces Cloneable and java.io.Serializable

Interestingly, the Sun documentation provides an example of a class that mimics what an Array object would contain as seen in Listing 8.

class A implements Cloneable, java.io.Serializable {

   public final int length = X;
      public Object clone() {
      try {
         return super.clone();
      } catch (CloneNotSupportedException e) {
         throw new InternalError(e.getMessage());
      }
   }
}

Listing 8

The clone( ) method will take the contents of one array and copy them into a second one. A code example is seen in Listing 9. The point of interest is the following line.

String days2[] = (String[]) days1.clone();

Note the syntax for the casting and the use of the clone( ) method.

public class ArrayLists {

   public static void main(String[] args) {

      String days1[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
      String days2[] = (String[]) days1.clone();

      for (String i: days2) {
         System.out.println(i);
      }

   }
}

Listing 9

When the code for Listing 9 is executed, you get the same output as you would have by listing the contents of the array days1[].

C:column24>"C:Program FilesJavajdk1.5.0_06binjava" ArrayLists
Sun
Mon
Tue
Wed
Thu
Fri
Sat
C:column24>

Conclusion

Arrays were part of the original Java specification. When Java 2 was released, the Java collections were introduced. The use of Arrays may be a bit dated; however, they are a great starting point in the discussion of collections. When designing Java applications, collections other than Arrays may well be the best choice, yet using Arrays to begin the exploration of how objects relate to collections is instructive.

While Arrays are technically objects, there are three limitations that prevent Arrays from being like other objects.

  • You cannot inherit from it
  • As you have seen, the syntax is a bit different (in other words, directly accessing attributes)
  • You cannot customize an array (in other words, create your own methods).

For example, consider the code in Listing 10.

public class ArrayLists extends Array {
   public static void main(String[] args) {
   }
}

Listing 10

When this code is compiled, the following output is generated.

C:column24>"C:Program FilesJavajdk1.5.0_06binjavac" ArrayLists.java
ArrayLists.java:1: cannot find symbol
symbol: class Array
public class ArrayLists extends Array {
                    ^
1 error
C:column24>

The compiler will not let the Array class be extended.

In next month's column, you will continue your exploration of how objects relate to various collections.

References

  • www.sun.com
  • Just Java 2, 6th Edition. Peter van der Linden. 2004, Sun Microsystems.

About the Author

Matt Weisfeld is a faculty member at Cuyahoga Community College (Tri-C) in Cleveland, Ohio. Matt is a member of the Information Technology department, teaching programming languages such as C++, Java, and C# .NET as well as various web technologies. Prior to joining Tri-C, Matt spent 20 years in the information technology industry gaining experience in software development, project management, business development, corporate training, and part-time teaching. Matt holds an MS in computer science and an MBA in project management. Besides The Object-Oriented Thought Process
, which is now in it's second edition, Matt has published two other computer books, and more than a dozen articles in magazines and journals such as Dr. Dobb's Journal, The C/C++ Users Journal, Software Development Magazine, Java Report, and the international journal Project Management. Matt has presented at conferences throughout the United States and Canada.





Page 2 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Sitemap | Contact Us

Rocket Fuel