Storing
User-Defined Classes in Collections
For the sake of simplicity,
the foregoing examples have stored built-in objects, such as String or Integer, in a collection. Of course, collections are not limited
to the storage of built-in objects.
Quite the contrary. The power of collections is that they can store any type of
object, including objects of classes that you create. For example, consider the
following example that uses a LinkedList
to store mailing addresses:
// A simple mailing list example.
import java.util.*;
class Address { private String name; private
String street;
private String city; private String state;
private String code;
Address(String n, String s, String c,
String st, String cd) {
name = n; street = s; city = c; state = st;
code = cd;
}
public String toString() {
return name + "\n" + street + "\n"
+ city + " " + state + " " + code;
}
}
class MailList {
public static void main(String args[]) {
LinkedList<Address> ml = new LinkedList<Address>();
// Add elements to the linked list.
ml.add(new Address("J.W. West",
"11 Oak Ave",
"Urbana", "IL",
"61801")); ml.add(new Address("Ralph Baker", "1142
Maple Lane",
"Mahomet", "IL",
"61853")); ml.add(new Address("Tom Carlton", "867 Elm St",
// Display the mailing list.
for(Address element : ml)
System.out.println(element + "\n");
System.out.println();
}
}
The output from the program
is shown here:
J.W. West
11 Oak Ave
Urbana IL 61801
Ralph Baker
1142 Maple Lane
Mahomet IL 61853
Tom Carlton
867 Elm St
Champaign IL 61820
Aside from storing a
user-defined class in a collection, another important thing to notice about the
preceding program is that it is quite short. When you consider that it sets up
a linked list that can store, retrieve, and process mailing addresses in about
50 lines of code, the power of the Collections Framework begins to become
apparent. As most readers know, if all of this functionality had to be coded
manually, the program would be several times longer. Collections offer
off-the-shelf solutions to a wide variety of programming problems. You should
use them whenever the situation presents itself.
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.