Declaration: Map or HashMap

Hi.
Question: I've read something about the declaration of a HashMap; some authors recommend (claims) that the variable containing the HashMap object should be declared to be of the interface Map. That's because of some methods that will take a Map as an argument.
Can anyone please give further explanations?
Thanks!

You mean:
// Some programmers say this is better:
Map stuff = new HashMap();
// ...than this:
HashMap stuff = new HashMap();The main reason for choosing the first option is that for the rest of the program it is only important that "stuff" is a Map. What implementation of Map is behind it, is an implementation detail (HashMap, TreeMap, ...).
By using the first option, it is also very easy to change the map type later, for example, if you decide you want a TreeMap instead of a HashMap.
Jesper

Similar Messages

  • Key value pair like map or hashmap

    What is the alternative to java map or hashmap, which store
    key value paris, in Flex.

    quote:
    Originally posted by:
    slaingod
    Typically you just use Object for those:
    var hash:Object = new Object;
    hash[key] = some_value;
    hash['string_key'] = some_value;
    not quite true, object does not give you api methods that all
    general purpose hasmap implementations do, for example get all
    keys, get all values etc .. so usually having a generic hasmap
    interface on top of dictionary/object its a good idea.

  • Map map = new HashMap(); -why doesnt this work in jdk 1.8.1

    Hi there,
    I'm trying to use a hashmap like this below:
    Map map = new HashMap();
    map.put("Carrots", new Integer(12));
    map.put("Potatoes", new Integer(30));
    map.put("Onions", new Integer(15));
    map.put("Apples", new Integer(40));
    map.put("Cherries", new Integer(300));
    the HashMap() does not exist in my API for some reason.
    Can anyone tell me why this may be?
    i'm using the hashmap with a stringtokenizer to search a text file line by line and increment how many times each keyword occurs.Sound efficient way of doing it?
    cheers,

    do you mean jdk 1.1.8?
    Map and the other Collections API were added in JDK 1.2. for JDK < 1.2, use Hashtable instead.

  • Mapping a Hashmap

    Hi erverybodey,
    i have little problem to understand the jdo mapping file.
    I have three classes:
    public class A

    Since you say that you have no idea why, I would recommend fully
    qualifying the map types.
    Behrmann Tilo wrote:
    Thanks for the answer,
    i have solved the Problem. The problem was that kodo my Map class with the
    Hashmap could't integrate directly in the mapping file from class A like
    this:
    <field name="valuesMap">
    <map key-type="Integer" value-type="MeasuredValue"/>
    </field>
    I get the exception bad map i have now idea why ok so i have model a
    one-one relationship in class A to my Map class (class B) and in the
    mapping file from class B a one-many relationship for the MeasuredValue
    objects it works fine. But my next problem is that kodo not insert the
    foreign keys for the MeasuredValue in the Database. (see posting above)
    thanks for your help
    Steve Kim
    [email protected]
    SolarMetric Inc.
    http://www.solarmetric.com

  • Difference between Map h = new HashMap() and HashMap h1 = new HashMap()

    Hi,
    I am new to Java.I am just confuse that what are the benifits or difference between these two approaches.
    1. Map map = new HashMap();
    2. HashMap hashMap = new HashMap();
    Please reply as soon as possible.
    Thanks
    Sachin

    Well the difference is that one declares the variable "map" as type "Map"
    The second declares the variable as type "HashMap"
    Why would you want to do this?
    Lets say at some point in the future, you decide you want the Map sorted. ie use a TreeMap instead of a HashMap.
    If you have used "HashMap" everywhere in your code, then you need to change all occurences of it to TreeMap.
    However if you just used "Map", the only dependency on "HashMap" is in this one line of code.
    Which do you think would be easier to change?

  • JAXB 2.0, XMLAdaptor and HashMap for customized mapping

    I have a requirement to implement a custom mapping of HashMap in JAXB. Basically I want to be able to use a HashMap structure to represent key/value pairs instead of the default List. So I need to be able to store (marshal) a HashMap structure into XML, and then be able to read (unmarshal) the XML back into a HashMap.
    I've discovered the XMLAdaptor class and I think this is the way to do it:
    https://jaxb.dev.java.net/nonav/jaxb20-pr/api/javax/xml/bind/annotation/adapters/XmlAdapter.html
    However, my knowledge of generics and annotations in 5.0, and XML schemas are somewhat elementary - so I'm a bit stuck.
    If someone has a complete working example of the HashMap example they show in the API doc linked above, I would greatly appreciate it if you could post it here.
    Otherwise, perhaps you could answer a couple of questions for me.
    1) I tried using the XSD directly from the example in the API doc (Step 2).
         <xs:complexType name="myHashMapType">
           <xs:sequence>
             <xs:element name="entry" type="myHashMapEntryType"
                            maxOccurs="unbounded"/>
           </xs:sequence>
         </xs:complexType>
         <xs:complexType name="myHashMapEntryType">
           <xs:simpleContent>
             <xs:extension base="xs:string"/>
           </xs:simpleContent>
           <xs:attribute name="key" type="xs:int"/>
         </xs:complexType>xjc complains when I generate the classes and says that the 'xs:attribute name=key' shouldn't be there. If I move it up into the 'xs:extension' node it works. But then I get strange XML when I create some key/value pairs and marshal them. The first XML node looks okay, but the rest of the List items start with '<xsi:entry ...', e.g.
    <entry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="myHashMapEntryType" key="key0">value0</entry>
    <xsi:entry xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="myHashMapEntryType" key="key1">value1</xsi:entry>
    ...So my first question is, what is the proper XSD to represent a HashMap with XML like the following:
         <hashmap>
             <entry key="id123">this is a value</entry>
             <entry key="id312">this is another value</entry>
          </hashmap>2) Now for the HashMap part of it; you need to create a class that extends XmlAdaptor<HashMap, MyHashMapType> with marshal and unmarshal methods. This is where I get a little fuzzy on exactly what these methods need to do. The example in the API doc doesn't show this.
    3) And finally; once I have all this in place, how do I actually marshal and unmarshal, presumably using the value types that I created instead of the value types that were auto generated by xjc? At least I think that's what I'm supposed to do.
    Thanks.

    Download the javaeetutorial5
    Under this path is a working example.
    \examples\jaxb\j2s-xmlAdapter-field
    I've tried following the bad example you sited, and even with a great deal of work it still fails to work.
    I think the example will help clarify how marshall and unmarshall methods are to be implemented. What would be really nice is for whoever wrote the example you sited to finish the job instead of expecting the reader of their documentation to figure it out.
    I fail to understand why JaxB has failed to directly support a collection so prevalent in its use as a HashMap. I also don�t know why they can�t support a Map interface that by default maps to a HashMap.
    Best of luck to you,
    Robert

  • How to declare class variable with generic parameters?

    I've got a class that declares a type parameter T. I know how to declare a static method, but this doesn't work for a static variable:
    public class Test< T >
        * Map of String to instances of T.
        * error: '(' expected (pointing to =)
        * <identifier> expected (pointing to () )
       private final static < T > Map< String, T > MAP = new HashMap< String, T >();
        * Get instance of type T associated with the given key.
       public final static < T > T getType( String key )
          return MAP.get( key );
    }Edited by: 845859 on Mar 20, 2011 11:46 AM

    jveritas wrote:
    I'm trying to create a generic polymorphic Factory class that contains boilerplate code.
    I don't want to have to rewrite the registration code every time I have a different return type and parameter.I haven't seen a case yet where that is reasonable.
    If you have hundreds of factories then something is wrong with your code, design and architecture.
    If you have a factory which requires large number of a varying input types (producing different types) then something is probably wrong with your code and design.
    A reasonable factory usage is one where you have say 20 classes to be created and you need to add a new class every 3 months. Along with additional functionality represented by the class itself and perhaps variances in usage. Thus adding about 3 lines of code to one class is trivial. Conversely if you have hundreds of classes to be created by the factory and you are adding them daily then it is likely that
    1. Something is wrong with the architecture which requires a new class every day.
    2. You should be using a dynamic mechanism for creation rather than static because you can't roll out a static update that often.
    More than that the idiom that leads to factory creation is different for each factory. A factory that creates a database connection is substantially different than the one used in dynamic rules logic processing. A generic version will not be suitable for both.
    Actualy the only case I know of where such a factory might be seem to be a 'good' idea is where someone has gotten it into their head that every class should be represented by an interface and every class created by a factory (its own factory.) And of course that is flawed.

  • How to use Dictionary or HashMap ?

    Hello Everyone,
    If I try to to declare
    HashMap<String,Integer> map = new HashMap<String,Integer>();
    I get this error
    <identifier> expected
    private HashMap<String,Integer> map = new HashMap<String,Integer>();
    When I try to define like this
    HashMap map = new HashMap<String,Integer>();
    I get this error
    (' or '[' expected
    HashMap map = new HashMap<String,Integer>();
    My class looks like this :-
    import java.util.*;
    public class WordCount
    HashMap map = new HashMap<String,Integer>();
    and if I try to do Dictionary the same error.
    Thanks for the help.

    Sounds like your version of Java is < 1.5. You need 1.5 for generics.
    Either upgrade to 1.5 or 1.6, or get rid of all the <type> stuff.

  • Help creating a semi-generic map

    Hi guys, i want to use a semi-generic map: its key should be a InetSocketAddress and its value can be anything.
    So i tried creating a Map<Entry<InetSocketAddress,? extends Object>> but it does not give me an option to create an Iterator.
    Can anyone please suggest a better way?

    Hi guys, i want to use a semi-generic map: its key
    should be a InetSocketAddress and its value can be
    anything.
    So i tried creating a Map<Entry<InetSocketAddress,?
    extends Object>> but it does not give me an option to
    create an Iterator.
    Can anyone please suggest a better way?Hi,
    Just declare the value as Object. E.g.
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("A key", new Integer(1));
        Iterator<Object> it = map.values().iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }Kaj

  • Request for clarification: Map.putAll

    I'm suggesting a clarification for the JDK's documentation of Map.putAll(), namely its implementation in HashMap, TreeMap etc.
    It would be very nice if the documentation stated explicitely whether putAll() uses put() in a loop to insert all entries from the source map into this map. I've verified that HashMap's putAll() implementation does just that, but AFAIK it's nowhere guaranteed!
    If you had this piece of information you'd know whether it suffices to override only put() in your own class if you derive from one of the standard maps.

    In a nutshell: because they've neglected to declare
    java.util.HashMap "final"!And why should they?
    java.util.HashMap extends java.util.AbstractMap, which
    has a well documented putAll() function that is
    guaranteed to call put() in a loop.
    AbstractMap was made to be derived from, thus
    the need to document the internals of the default
    implementations.Documenting the internals is not necessary for a class that is made to be derived from. The documentation of putAll() is there to help programmers, not as a requirement of an extendable class.
    Since java.util.HashMap is not final, the same
    logic applies here:
    in order to know exactly which function to override,
    you need to know its internals.I don't agree with this statement. It is more correct to say 'in order to know which functions need not be overridden, you need to know its internals'.
    I agree that now I cannot rely on the unknown
    implementation, thus I'm forced to override putAll()
    in addition to put().Which is probably what the implementors of HashMap intended.
    But IMO it is a design flaw of the Collections
    framework not to declare all concrete implementations
    as final.You have yet to show how this is true.
    Doing so would have given the library developers full
    freedom to change implementations as they please.
    You'd still have the "Abstract" classes to derive
    from. The developers already have full freedom to change implementations as they please. If their changes breaks code that relies upon an undocumented implementation, then that is the fault of the programmer extending the class. Also, if you want to extend a class with a documented internal implementation then, like you said, you still have the "Abstract" classes to derive from.
    But no use crying over spillt milk, it was just
    something that struck me as mildly annoying...It seems to me that you are annoyed that you don't know whether or not you should override putAll(). Well, I say that if the documentation does not give you enough information for you to answer no, then the answer obviously is yes, you should. Developers cannot be expected to tell you that explicitly in the documentation.

  • Hashmap's empty

    Hi dudes
    I start at the beginning^^
    I'm quite new in java and I have to write an application as a practice in java, which analyses txt files in a lot of zip files about their DayLightSaving handling (^^) . There are 4 types of txt files ... (ceva.txt / ice.txt / ...) and I have for each type a seperate button/method... I have a method which goes through all Zip Files and reads out the txt files and store them in a Vector of ZipEntries and returns it.
    an other class (the GUI class) will get this information for editing... So if i want to reaccess these txt files I have to create a new stream for the zip files because the zipentries don't know from which file it comes^^ .
    So for this I made a HashMap with the entries <ZipEntry, String (pathOfZipFile)>
    this map will be filled when the application reads out the zip files at the first time. The hashmap fill in works ( saw it in debug mode ) but as soon as the process stops and the GUI will be visible again the Hashmap is lost.
    Does anybody know why this happens or another/better way to do what I want to do?
    I hope u can understand what I wrote^^

    By the way, am I missing something with the pairs of carets (^^) all over the >place? Is this a new lingo the kids are using nowadays? :)I use this as an emoticon :) but you can ignore it anyway
    I hope this part is useful , thank you for the quick response
         private HashMap<ZipEntry, String> hashmapEntryZip; //declaration of the Hashmap
         public AnalyserCore()
              mainZipDir = new File(AnalyserGUI.ZIP_DIR);
              zipFileList = mainZipDir.listFiles();          
              hashmapEntryZip = new HashMap<ZipEntry, String>();
            /** Method which reads out the zips and stores the txt's in the vector and hashmap*/
         public Vector<ZipEntry> analyzeData(String mode)
              //StringBuffer tempBuffer = new StringBuffer();     //AnalyseArea Output         // buffered buffer^^ for temporarly saving the data ...
              //StringBuffer textBuffer = new StringBuffer();     //temp File Output               //... and write it to this buffer
              Long dateBevor = Calendar.getInstance().getTimeInMillis(); //(start time) for time used statistics
              Vector<ZipEntry> fileArray = new Vector<ZipEntry>();
              ZipEntry entry ;
              fileTemporaryOutput = new File("ch/schann/analyse/" + mode + ".txt");
              try
                   fileTemporaryOutput.createNewFile(); //Create the temporary File
                   //FileWriter writer = new FileWriter(fileTemporaryOutput);               
                   for ( int p = 0; p < zipFileList.length; p++ )
                        String str = new String();
                        str += "\n[ zip ] File: " + (p+1) + "(" + zipFileList[p].getName() + ") ...\n";
                        str += "-------------------------\n";
                        // File reading whithin the Zipfile
                        zipReading = new ZipInputStream(new FileInputStream(zipFileList[p]));
                        entry = zipReading.getNextEntry();
                        int fileIndex = 0;
                        while (entry != null)
                             String filePath = entry.getName();
                             int lastSlashPos = filePath.lastIndexOf("\\");
                             String fileName = filePath.substring(lastSlashPos + 1);
                             String meterReadout = fileName.substring(0, 2);
                             if (meterReadout.equalsIgnoreCase(mode))
                                  fileIndex++;
                                  fileArray.add(entry);
                                  this.hashmapEntryZip.put(entry, zipFileList[p].getAbsolutePath());
                                  str += "[ txt ]File " + fileIndex + ":" + filePath + "...\n";
                             entry = zipReading.getNextEntry();
                        str += "[* NO MORE ELEMENTS *]\n";
                        //writer.write(str);
                        //writer.flush();
                        System.out.println(str);
                        zipReading.close();
                   Long dateAfter = Calendar.getInstance().getTimeInMillis();//(end time) for time used statistics
                   System.out.println("Time Used: " + (dateAfter - dateBevor) + "ms");
              catch(Exception e)
                   System.out.println("\n--------------\n" + e.getMessage());
                   e.printStackTrace();
              /*catch(FileNotFoundException ex)
                   System.out.println("[File Not Found:] " + ex.getMessage());
              catch ( IOException e)
                   System.out.println("[IO -ERROR:] " + e.getMessage());
              return fileArray;
         }

  • "Economizing" in a list of maps with identical keys (like a database table)

    Hi there!:
    I've been checking this forum for information about something like what I state in the title of this message, but haven't found such a specific case. I'm commenting my doubt below.
    I'm working with a list of maps whose keys are exactly the same in all them (they're of type String). Indeed it could be considered an extrapolation of a database table: The list contains maps which act as rows, and every map contains keys and values which represent column names and values.
    However, this means to repeat the same key values on every map and this spends memory. Right, maybe it's not such a big spent, but since the list can contains thousands of maps, I think that it would be better to choose a more "economical" way to achieve the same result.
    I had thought about building a class which stored everything as a list of lists and, internally, it mapped that String keys with the corresponding Integer indexes of every list. But then I realized that maybe I was re-inventing the wheel, because it's very probable that someone has already made that. Maybe is there a class on the Core API which allows that?
    Thank you very much for your help.

    Well, after re-reading the Java tutorial which is located in the Sun website I've came to a conclusion which I should have before, when I thought about using StringBuffers as keys of the maps instead of Strings.
    I'm so used to build Strings using literals instead of the "new String ()" constructor (just as everyone) that I had forgotten that, as it happens with any kind of object but not the primary data types, Strings are not passed to the methods by value, but by reference. The fact of them being immutable made me think that they were passed by value.
    Apart of that, my problem also was that using literals I was creating different String objects every time, despite the fact that they were equal about their content (making 400 different keys called "name" for example)
    In other words, I was doing something like this:
    // It makes a list of maps which will contain maps of boy's personal data (as if they were "rows" in a table).
    List <Map <String, Object>> listData = new ArrayList <Map <String, Object>> (listBoy.size ());
    // It loops over a list of Boy objects, obtained using EJB.
    for (Boy boy : listBoy) {
         // It makes a new map containing only the information which I'm interested on from the Boy object.
         Map <String, Object> map = new HashMap <String, Object> (2);
         map.put ("name", boy.getName ());
         map.put ("surname", boy.getSurname ());
         // It adds the map to the list of data.
         listData.add (map);
    }Well, the "problem" here (being too demanding, but I'm :P ) is that I was adding all the time new Strings objects as keys in every map. The key "name" in the first map was different from "name" in the second one and so on.
    I guess that my knowledge got messed at certain point and thought that it was impossible to use exactly the same String object in different maps (the reference, not the same value!). Thus, my idea of using StringBuffers instead.
    But thinking about it carefully, Why not to do this?:
    List <Map <String, Object>> listData = new ArrayList <Map <String, Object>> (listBoy.size ());
    // It makes the necessary String keys previously, instead of using literals on every loop later.
    String name = "name";
    String surname = "surname";
    for (Boy boy : listBoy) {
         // It uses references (pointers) to the same String keys, instead of new ones every time.
         Map <String, Object> map = new HashMap <String, Object> (2);
         map.put (name, boy.getName ());
         map.put (surname, boy.getSurname ());
         listData.add (map);
    }Unfortunately, the "hasCode" method on String is overloaded and instead of returning the typical hash code based on the single ID of the object in memory, it returns one based on its content. That way I can't make sure that the "name" key in one map refers to the same object in memory than another one. I know, I know. The common sense and the Java documentation confirm that, but had loved having an empiric way to demonstrate it.
    I guess that using "javap" and disassembling the generated bytecode is the only way to make sure that it's that way.
    I believe that it's solved now :) (if no one tells me the contrary). I still am mad at myself for thinking that Strings were passed by value. Thinking about it now it had no sense!
    dannyyates: It's curious because re-reading every answer I think that you maybe were pointing to this solution already. But the sentence "you put the +same+ string" was a little ambiguous for me and thought that you meant putting the same String as "putting the same text" (which I already was doing), not the same object reference (in other words, using a common variable). I wish we could have continued discussing that in depth. Thanks a lot for your help anyway :) .

  • Missing Value using HashMap and StringTokenizer

    class StringToken
         String Message = "a b Germany";
         HashMap <String,String> map;
    StringTokenizer token;
         public StringToken()
              try
              token = new StringTokenize(Message);
                   map = new HashMap <String,String>();
                   map.put("a","Adelaide");
                   map.put("b","Auckland");
    while (token.hasMoreToken())
                        System.out.print (map.get(pesan.nextToken())+" ");          
              catch(Exception e)
         public static void main(String[] args)
              new StringToken();
    The output like this :
    Adelaide Auckland null
    What i want like this:
    Adelaide Auckland Germany
    The problem is,How to display all value of Message? cos There's no Germany key..i want to make some condition like this, if there's no key in the Hashmap, the value still displayed originally..
    At my code the problem is, if there's no key in hashmap,output wont display the word..
    Thanks Guys...

    Two options:
    1) Instead of
    System.out.print(map.get(pesan.nextToken()));do
    String token = pesan.nextToken();
    String value = map.get(token);
    if (value==null) value = token;
    System.out.print(value);2) Implement a new Map which provides this behavior.
    Cheers

  • How to get the value in a hashmap with a key of expression "123-456"?

    Hi all,
    I new to java and having a problem with getting values from a hashmap.here is the code which i wrote
    Map map = new HashMap();
    int m = 123;
    int n = 456;
    String key = String.valueOf(m) + "-" + String.valueOf(n);
        map.put(key, true);
        Now i am trying to get the value and i get an exception
    boolean b = map.get(String.valueOf(m) + "-" + String.valueOf(n));Can someone help me how to pass this expression as key in the hashamp

    Hi corlettk,
    Thanks for your reply. I have defined my map as Map<String, Boolean> selectedIds = new HashMap<String, Boolean>();
                selectedIds.put("123-456", true);           
                int m=123; int n=456;
                                     selectedIds.put(String.valueOf(m) + "-" + String.valueOf(n),true);
                boolean viv = selectedIds.get("String.valueOf(m)-String.valueOf(n)");
                System.out.println(viv);
                My problem is the hashmap key must be set dynamically ("123-456" is just an example) and when i get the value i should be able to pass those varibales in an expression correctly. Please let me know how can i pass an expression like the one above as a hashmap key. Please advise.

  • How to keep the original sequence of a map

    I want the equivalent of a Hashtable or Map class (I need keys and corresponding objects) which, once fully populated, will guarantee to get the key/object pairs back out using the order in which they were added, rather than by sort order of the keys.
    ( The bigger objective is to compare two such collections, A and B, to see which key/object pairs exist in A but not B, and which exist in B but not A. However, for presentation purposes, I need to keep the original order in which everything was read.)
    What's the most efficient way to do this ? I'm sure I've missed something really simplistic but, hey, it's Monday......

    There is no way to retrieve objects from any map in the order they were incerted unless you add some logic to the way you are incering it.
    Here is an example of such logic, where I want to retrieve "states" in the same order as I put them:
         public static void main(String[] args){
              HashMap map = new HashMap();
              map.put("1" + "PA", "Pensylvania");
              map.put("2" + "NJ", "New Jersey");
              map.put("3" + "CA", "California");
              map.put("4" + "TX", "Texas");
              LinkedList ls = new LinkedList(map.keySet());
              Collections.sort(ls);
              Iterator iter = ls.iterator();
             String stAbbrv = null;
              while (iter.hasNext()){
                   stAbbrv = (String)iter.next();
                   System.out.println(stAbbrv.substring(1) + " - " + map.get(stAbbrv));
         }the output is:
    PA - Pensylvania
    NJ - New Jersey
    CA - California
    TX - TexasHope it helps
    Alex
    [email protected]

Maybe you are looking for