Java Forum / General / November 2007
static hashtable with conent?
Kevin - 24 Nov 2007 19:44 GMT Did not find out the answer after some google:
how can we create a static hashtable with some initial values there?
static Hashtable ht = new Hasthable();
will only create a empty one. Suppose I want to put some Integer values as keys and values of this hashtable, how can I do that?
The reason for it is that I am writing a "utility" class, with all the functions as static. These functions will need to check a fixed hashtable for some operations.
Thanks a lot. :-)
Lew - 24 Nov 2007 19:55 GMT > how can we create a static hashtable with some initial values there? > [quoted text clipped - 6 lines] > functions as static. These functions will need to check a fixed > hashtable for some operations. Use a static initializer.
Use HashMap, not Hashtable, usually. This is especially true if, as seems to be true for you, no one is writing to the table.
If that is the case, use a static method to return the Map (as a Map, not a HashMap) via Collections.unmodifiableMap(). Otherwise client code will be able to alter the contents of your Map.
 Signature Lew
Lars Enderin - 24 Nov 2007 19:55 GMT Kevin skrev:
> Did not find out the answer after some google: > [quoted text clipped - 8 lines] > functions as static. These functions will need to check a fixed > hashtable for some operations. Write the code to initialize the table inside a static { ... } block. Note that Hashtable is not recommended. Use some version of Map instead.
Mike Schilling - 24 Nov 2007 19:57 GMT > Did not find out the answer after some google: > [quoted text clipped - 4 lines] > will only create a empty one. Suppose I want to put some Integer > values as keys and values of this hashtable, how can I do that? Use a static init block (And use a HashMap; Hashtable is obsolete)
static Map map; static { map = new HashMap(); map.put("if", IF_TOKEN); map.put("else", ELSE_TOKEN); ... }
Kevin - 24 Nov 2007 20:29 GMT It works. Thanks so much guys!
Owen Jacobson - 25 Nov 2007 00:07 GMT >> Did not find out the answer after some google: >> [quoted text clipped - 15 lines] > ... > } There is a trick for emulating (sort of) map literals in Java that might be useful here:
static Map<String, Whatever> map = new HashMap<String, Whatever> () {{ put ("if", IF_TOKEN); put ("else", ELSE_TOKEN); // ... }};
It does have the cost of requiring one more class to be loaded. It will also confuse reflection-based code that expects the 'map' field to _be_ a specific subtype rather than _assignable to_ a specific subtype. OTOH, I find both of those concerns are rarely important in my own code.
Cheers, O
Mike Schilling - 25 Nov 2007 01:36 GMT >>> Did not find out the answer after some google: >>> [quoted text clipped - 30 lines] > subtype. OTOH, I find both of those concerns are rarely important in > my own code. It'll also confuse the hell out of anyone who's never seen it before. I got it eventually, but it's not really obvious that "{{" introduces an init block in an anonymous class.
Owen Jacobson - 25 Nov 2007 03:15 GMT >>>> Did not find out the answer after some google: >>>> [quoted text clipped - 34 lines] > it eventually, but it's not really obvious that "{{" introduces an init > block in an anonymous class. *grin*
That's about what my initial reaction to it was. It's also nowhere near as elegant as Perl or Python's dictionary literals.
Lew - 25 Nov 2007 03:27 GMT >>> There is a trick for emulating (sort of) map literals in Java that >>> might be useful here: [quoted text clipped - 10 lines] >>> subtype. OTOH, I find both of those concerns are rarely important in >>> my own code. "Mike Schilling" said:
>> It'll also confuse the hell out of anyone who's never seen it before. >> I got >> it eventually, but it's not really obvious that "{{" introduces an init >> block in an anonymous class.
> *grin* > > That's about what my initial reaction to it was. It's also nowhere near > as elegant as Perl or Python's dictionary literals. You could make it more "literal" by wrapping the assignment with a Collections.unmodifiableMap(), no?
static Map<String, Whatever> map = Collections.unmodifiableMap( new HashMap<String, Whatever> () { { put ("if", IF_TOKEN); put ("else", ELSE_TOKEN); // ... } } );
If there's one thing I got from Owen's suggestion it's that I'll never know everything there is to know about Java.
Ugly as it is to many people, Java's anonymous class syntax is bloody powerful.
 Signature Lew
Patricia Shanahan - 25 Nov 2007 03:40 GMT ...
> There is a trick for emulating (sort of) map literals in Java that might > be useful here: [quoted text clipped - 9 lines] > a specific subtype rather than _assignable to_ a specific subtype. OTOH, > I find both of those concerns are rarely important in my own code. What is the advantage of this over the static initializer approach? It is very clever, and I don't immediately see anything to compensate for the cleverness.
Patricia
Stefan Ram - 25 Nov 2007 03:55 GMT >What is the advantage of this over the static initializer approach? It >is very clever, and I don't immediately see anything to compensate for >the cleverness. It can be used, where an /expression/ for a map is wanted.
For example, in a call:
f( new HashMap(){{ put(a,b); put(c,d) }} );
. In the context »f( ... )«, a sequence of statements is not allowed.
Mike Schilling - 25 Nov 2007 05:54 GMT >> What is the advantage of this over the static initializer approach? >> It is very clever, and I don't immediately see anything to [quoted text clipped - 7 lines] > > . In the context »f( ... )«, a sequence of statements is not allowed. Or one could simply say
Map map = new HashMap(); map.put(a,b); map.put(c,d); f(map);
Or even introduce a private method to create and populate the map, if it's considered important to distinguish that part of the code from the rest..
By the way, note that Patricia is (quite correctly here) using "clever" disparagingly. That isn't done nearly often enough.
Owen Jacobson - 25 Nov 2007 06:35 GMT On Nov 24, 9:54 pm, "Mike Schilling" <mscottschill...@hotmail.com> wrote:
> >> What is the advantage of this over the static initializer approach? > >> It is very clever, and I don't immediately see anything to [quoted text clipped - 20 lines] > By the way, note that Patricia is (quite correctly here) using "clever" > disparagingly. That isn't done nearly often enough. In the context of a method call, I would prefer Mike's form. In the context of initializing a map constant I think I'd prefer to keep the initializer scoped to the map and only the map, rather than to the containing class.
Patricia Shanahan - 25 Nov 2007 15:10 GMT ...
> Or one could simply say > [quoted text clipped - 8 lines] > By the way, note that Patricia is (quite correctly here) using "clever" > disparagingly. That isn't done nearly often enough. Maybe "disparagingly" is a bit stronger than I meant. I have really mixed feelings about this type of thing.
On the one hand, I admire creativity, and enjoy solving puzzles. From that point of view, the anonymous class version is just plain *fun*.
On the other hand, in real code I greatly prefer simplicity and obviousness. Even if something clever looks shorter in a newsgroup posting, it would often be longer in real code, because of the comment explaining it.
Even for the call situation, I would go with the code Mike suggested or its private method call equivalent.
This really comes down to a model of programming as writing that must communicate its meaning to two very different audiences. One audience is the compiler, and other programming tools. The other audience is all programmers who will ever read the code, my future self included.
The two methods communicate equally well with the compiler. The method Mike suggests perhaps communicates better with refactoring tools - Eclipse could convert it between the in-line and method call versions.
But the really important issue is that many programmers will have to stop and puzzle out the anonymous class version. I understood it once I looked at it and thought about it, but I would not have read straight through it, thinking only about whether the initial contents of the map are appropriate, the way I would the simpler, more explicit versions.
Patricia
Stefan Ram - 25 Nov 2007 17:54 GMT >This really comes down to a model of programming as writing >that must communicate its meaning to two very different >audiences. One audience is the compiler, and other programming >tools. The other audience is all programmers who will ever read >the code, my future self included. Even programmers are not all alike.
What is »readable« to one, depends on his background.
When one comes to Java and the only language one has ever used before was Haskell, one will deem other coding constructions as »simple« or »obvious« than someone who only has been programming in Pascal before. When learning Java, as a first language, people with a background in mathematics will consider other notations readable than English majors.
»I've found that some of the best developers of all are English majors. They'll often graduate with no programming experience at all, and certainly without a clue about the difference between DRAM and EPROM.
But they can write. That's the art of conveying information concisely and clearly. Software development and writing are both the art of knowing what you're going to do, and then lucidly expressing your ideas.«
http://praisecurseandrecurse.blogspot.com/2007/03/english-majors-as-programmers.html
Lew - 25 Nov 2007 18:08 GMT >> This really comes down to a model of programming as writing >> that must communicate its meaning to two very different [quoted text clipped - 24 lines] > > http://praisecurseandrecurse.blogspot.com/2007/03/english-majors-as-programmers.html It might not be unreasonable to expect professional practitioners of programming with a particular language such as Java to be able to read the constructs of that language. Even "advanced" constructs with lots of parentheses or whatever.
If you can't stand the heat, don't be a chef.
 Signature Lew
Patricia Shanahan - 25 Nov 2007 20:05 GMT ...
> It might not be unreasonable to expect professional practitioners of > programming with a particular language such as Java to be able to read > the constructs of that language. Even "advanced" constructs with lots > of parentheses or whatever. > > If you can't stand the heat, don't be a chef. It might not be unreasonable to expect readers of English to be able to read the constructs of that language. Even "advanced" constructs with lots of subordinate clauses or whatever.
I can stand the heat but I would rather my readers did not have to.
Patricia
Lew - 25 Nov 2007 21:10 GMT > .... >> It might not be unreasonable to expect professional practitioners of [quoted text clipped - 7 lines] > read the constructs of that language. Even "advanced" constructs with > lots of subordinate clauses or whatever. I was referring to *professionals*. A better analogy would be (English-language) attorneys, who are expected to do exactly that with English, or rather the specialized form of English informally called "legalese". If you cannot parse advanced English constructs such as lots of subordinate clauses, you should not expect to be paid as a legal professional.
We're supposed to be knowledgeable. It's why we get *paid* to do this.
 Signature Lew
Lew - 25 Nov 2007 21:11 GMT > I was referring to *professionals*. A better analogy would be > (English-language) attorneys, who are expected to do exactly that with > English, or rather the specialized form of English informally called > "legalese". If you cannot parse advanced English constructs such as > lots of subordinate clauses, you should not expect to be paid as a legal > professional. Oh, I'm sorry, that was replete with subordinate clauses. I hope I'm not being unreasonable in expecting people to be able to read them.
 Signature Lew
Mike Schilling - 26 Nov 2007 02:02 GMT >> I was referring to *professionals*. A better analogy would be >> (English-language) attorneys, who are expected to do exactly that [quoted text clipped - 5 lines] > Oh, I'm sorry, that was replete with subordinate clauses. I hope I'm > not being unreasonable in expecting people to be able to read them. I think, though I'm not going to insist upon this (not being in a position to do so, even were I so inclined to; Usenet, as a free medium, somewhat paradoxically places fewer demands on the reader than a paid one does. Having no money invested in the reading of a post leaves the reader free to quit it at a moment's notice for any reason at all with no sense of having lost any investment. This places a substantial burden on an author who desires a wide audience to avoid being either dull or unpleasant. and certainly to avoid unreasonable demands), that Patricia, whose general good sense is, I should think, well established in these parts, at least to the extent that a history of posts can be said to establish a picture of their author (this being another subject which is open to debate: certainly, the amount of time that, for instance, sarcasm goes undetected, argues that Usenet posts are a very imperfect vehicle for communicating the sort of subtleties by which people, in the common world of face-to-face communication, use to form opinions of their fellows), has the right of it here; that while the grammars that underlie both natural languages like English and artificial languages like Java are capable of forming expression and statements (and here we are lucky that both terms, while not synonymous in the two realms, in this case can be used as if they were) of arbitrarily high complexity, simply by applying the generation rules repeatedly, that in both cases the idioms which are understood easily and naturally come from a constrained application of those rules, and that using examples lying outside the standard idioms places upon our readers, whose ready understanding is in fact in our own interests as well as in theirs, an unnecessary burden, and thus should be avoided or at least severely minimized, absent any significant advantage to be found in their use.
Lew - 26 Nov 2007 05:27 GMT > I think, though I'm not going to insist upon this (not being in a position > to do so, even were I so inclined to; Usenet, as a free medium, somewhat [quoted text clipped - 22 lines] > unnecessary burden, and thus should be avoided or at least severely > minimized, absent any significant advantage to be found in their use. Pure brilliance. Bravo!
As I stated before, I, at least, have acknowledged the validity of Patricia's argument in favor of clarity over cleverness.
To a point. I doubt very much that I will be afraid to use anonymous classes; they are occasionally a necessary idiom. In some rare cases, although it has yet to be necessary for any program I've worked on, I can imagine needing to define an anonymous class constructor.
I am not arguing for obscurity for obscurity's sake, nor for cleverness for cleverness's sake. It's just that in Java the anonymous class idiom is the heart of certain closure-like expressions. If an anonymous class is the cleanest way to accomplish such a pseudo-closure, I am going to use it, and I will expect competent Java programmers to understand it. If I were hiring a Java programmer, I would test them on their ability to understand anonymous classes as part of the screening process.
OTOH, I have read at least one assertion that nested classes represent a security hole in Java code. I am skeptical of that claim, but it's out there.
 Signature Lew
Patricia Shanahan - 26 Nov 2007 05:44 GMT >> I think, though I'm not going to insist upon this (not being in a >> position to do so, even were I so inclined to; Usenet, as a free [quoted text clipped - 46 lines] > security hole in Java code. I am skeptical of that claim, but it's out > there. I am all in favor of anonymous inner classes - when an anonymous inner class is the simplest, clearest, or otherwise best way of expressing something.
My objection was to an unconventional use of one in a situation in which there is an alternative that is just as good technically and that seems simpler and clearer to me.
Code should be as simple as possible, but no simpler.
Patricia
Patricia Shanahan - 25 Nov 2007 21:57 GMT >> .... >>> It might not be unreasonable to expect professional practitioners of [quoted text clipped - 16 lines] > > We're supposed to be knowledgeable. It's why we get *paid* to do this. Having had to review and sign patent applications, I absolutely and totally reject any idea of taking legalese as any sort of model for my programming style.
Of course we are supposed to be knowledgeable, though as a student I am not being paid to do anything. I *can* read clever code, if I have to. My bachelor's degree was in mathematics, which tends to very succinct notation.
I just don't see why I should make my code any harder to read than it has to be, and I can see a lot of benefits to making it as simple and clear as possible. That way, readers can focus on important stuff, such as whether the map has the right initial contents, rather than details such as the initialization method.
Patricia
Lew - 25 Nov 2007 22:19 GMT > I just don't see why I should make my code any harder to read than it > has to be, and I can see a lot of benefits to making it as simple and > clear as possible. That way, readers can focus on important stuff, such > as whether the map has the right initial contents, rather than details > such as the initialization method. Your points are well reasoned and quite convincing.
 Signature Lew
Lasse Reichstein Nielsen - 25 Nov 2007 10:56 GMT >> Did not find out the answer after some google: >> [quoted text clipped - 15 lines] > ... > } I would prefer a static method returning the map:
static Map map = createMap();
private static final Map createMap() { Map map = new HashMap(); map.put("if", IF_TOKEN); map.put("else", ELSE_TOKEN); }
Or perhaps create a builder: static Map map = new MapBuilder(new HashMap()).put("if", IF_TOKEN) .put("else", ELSE_TOKEN) .toMap(); if it is something that is done often.
I would prefer not to use the clever anonymous subclass of HashMap with an initializer. It's something that's bound to bite you in the posterior sooner or later. E.g., if you try to send the map to another process using serialization - then the receiver should also have the same anonymous class available. That can be alleviated using static Map map = new HashMap(new HashMap(){{ put("if", IF_TOKEN); put("else", ELSE_TOKEN); }}); i.e., using it more like a builder. Still far too clever to be readily readable.
However, it seems that the actual problem being solved is a translation between strings and some contstants/enums/whatever. That the translation is performed by a map is an implementation detail.
I would create a method static Token textToToken(String text) { //... It could initialize its map lazily, or it could use a completely separate apporach.
/L 'but Map literals would be nice :)'
 Signature Lasse Reichstein Nielsen - lrn@hotpop.com DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html> 'Faith without judgement merely degrades the spirit divine.'
Lew - 25 Nov 2007 13:32 GMT > However, it seems that the actual problem being solved is a translation > between strings and some contstants/enums/whatever. > That the translation is performed by a map is an implementation detail. If that's the case, then an enum with a well-crafted valueOf() would do the trick.
 Signature Lew
Mike Schilling - 25 Nov 2007 17:06 GMT >> However, it seems that the actual problem being solved is a >> translation between strings and some contstants/enums/whatever. [quoted text clipped - 3 lines] > If that's the case, then an enum with a well-crafted valueOf() would > do the trick. Actually, mapping strings to constanxcts was my example of a map. The OP never told us what his map was for.
Lew - 25 Nov 2007 17:15 GMT >>> However, it seems that the actual problem being solved is a >>> translation between strings and some contstants/enums/whatever. [quoted text clipped - 5 lines] > Actually, mapping strings to constanxcts was my example of a map. The OP > never told us what his map was for. It occurs to me that such a map could be part of the implementation of an enum's valueOf() method.
 Signature Lew
Roedy Green - 25 Nov 2007 03:41 GMT On Sat, 24 Nov 2007 11:44:25 -0800 (PST), Kevin <happy_singapore@yahoo.com.sg> wrote, quoted or indirectly quoted someone who said :
>how can we create a static hashtable with some initial values there? > >static Hashtable ht = new Hasthable(); > >will only create a empty one. Suppose I want to put some Integer >values as keys and values of this hashtable, how can I do that? HashTable is rarely used anymore. see http://mindprod.com/jgloss/hashtable.html http://mindprod.com/jgloss/hashmap.html
 Signature Roedy Green Canadian Mind Products The Java Glossary http://mindprod.com
Stefan Ram - 25 Nov 2007 15:55 GMT >will only create a empty one. Suppose I want to put some Integer >values as keys and values of this hashtable, how can I do that? I have written a library to parse map expressions. For example:
public final class Main { public static void main( final java.lang.String argv[] ) { final IntMap map = new IntMap( "1=7 2=4" ); java.lang.System.out.println( map.valueOf( 1 )+ map.valueOf( 2 )); }}
/* prints: 11 */
class IntMap { final java.util.Map map;
public IntMap( final java.lang.String arg ) { this.map = de.dclj.ram.notation.unotal.RoomFromModule.room // see http://www.purl.org/stefan_ram/pub/junotal_tutorial ( "< " + arg + " >" ); }
public int valueOf( final int arg ) { return java.lang.Integer.valueOf ( this.map.get( java.lang.String.valueOf( arg )).toString() ); }}
Free MagazinesGet these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...
|
|
|