Stan Goodman wrote:
Hey Stan:
I'll describe the problem in more detail:
Given a file containing groups of text lines, each group falling
naturally into a structure like a linked list. In the first line of
each such group is embedded an identifying string, which is unique. I
would like to be able to make an object of each such group (a linked
list), and idetify it by this unique string. I would like to set all
this up in the first phase of the program. In a later phase, the
program will generate a string identical to one of the unique strings,
and I will need to access the corresponding group to process it..
In this case, what you want to do is to create an object that
encapsulates one linked-list element of data, which has an assignable
String field in which you can keep your unique identifier. At its most
basic, you'll probably put together a class something like this:
public class MyListElement {
public String id = null; // Your identifier will go here
public MyListElement next = null;
// ^ Pointer to the next element in the list
public MyListElement(String id) {
this.id=id;
}
public MyListElement next() {
return next;
}
public boolean hasID(String s) {
return id.equals(s);
}
}
With this sort of object, you'll be able to "walk" the list using a
loop such as:
// "head" is first element in the list
MyListElement mle = head;
while (!mle.hasID(id_we_are_looking_for)) mle=mle.next();
Since I posted the question, I have read a bit about hashtables; in my
present stage of ignorance, that seems a good approach, especially as
it has been suggested by Marco. Is that right? Is there another
suggestion?
Using a HashTable certainly has its own benifits, but it isn't a linked
list. That is okay however -- you probably don't strictly _need_ a
linked list to store and retreive your data anyhow. HashTable has the
benifit of being able to take care of the key matching for you.
The only potential disadvantage of HashTable is that it stores elements
of the type java.lang.Object, so you don't necessarily have forced
type-safety as you do in the example above. This isn't necessarily a
problem if you're careful to ensure that only your object type is
written to the table, and you cast Objects read from the table back to
your object type before using them.
HTH!
Brad BARCLAY