TreeMap or HashMap question

Hi,
I noticed that if I use the put method with the string as the parameter for any objectB, I would get that objectB back by using the get function with that string. However, if I use the put method as an objectA as a parameter for any objectB, I would not get back objectB even if objectA all the fields exactly the same. Is there a way to somehow override the checking mechanism like a comparator? Thanks.

To use a custom object as a key, you must override the following methods in Object
equals()
hashcode()

Similar Messages

  • A TreeMap and ArrayList question

    I am considering using a TreeMap structure with a String as my key and an ArrayList<Record> as my value. After doing some searching and not quite finding the assurance I desired, I am looking for anyone's guidance on my approach. Allow me to briefly explain my situation.
    I am writing a program which reads a entry log and breaks the information into a more usable form (in particular, separated by each individual). I do not know before hand the names of the people I may encounter in the log, nor how many occurances of their name I may find. Also, it is safe to assume that no one person's name is the same for two different people. I wish to be able to call up a person's name and view all records associated with them. I felt the use of a TreeMap would be best in the event that I wish to list out a report with all individuals found, and such a listing would already be in alphabetical order.
    In summation, is my approach of making a TreeMap<String, ArrayList<Record>> an acceptable practice?
    Thank you for your time.

    Puce wrote:
    >
    If there's the slightest chance, OP, that you'll have to do something other than simply look up records by name, consider an embedded DB. If there's the slightest chance that Ron Manager will come along on Monday and say "Good job! Now, can we look up records by date?" or something, consider an embedded DB."Embedded DB" is something different than "in-memory DB" though. An embedded DB is persistent while a in-memory one is not. If you use an embedded DB, you need to synchronize it after restart with your other data sources, and it will use disk space as well. There are use case for embedded DBs and others for in-memory DBs. Hard to say which is the case here, without knowing more.The OP "isn't allowed" to use a database, which almost certainly means he's not allowed to install any more software on the system, eg, MySQL. So an in-process database is the way to go. Whether it's persistent or not is irrelevant. "Embedded" and "in-memory" are not opposites. By "embedded" we really mean in-process. Do you know of any databases which can run in-process but not in-memory? How about in-memory but not in-process? In reality, we're talking about the same products, configured slightly differently.

  • Hashmap Question

    I have this method that needs to return a String of possible exits of a room, by reading it from the HashMap.
        public String getExitstring()
            String returnString = "Exits:";
            Set <String> keys = exits.keySet();
            for(String exit : keys)
                returnString += " " + exit;
            return returnString;
        }However, it gives me the error "cannot find symbol - class Set". I'm lost here, since it's a method according to the JavaDoc. And yes, I import java.util.HashMap.

    Grawl wrote:
    However, it gives me the error "cannot find symbol - class Set". I'm lost here, since it's a method according to the JavaDoc. And yes, I import java.util.HashMap.Why would you think that importing HashMap would also import Set? They're not the same class. To use Set you need to import java.util.Set
    And what do you mean that Set is a 'method' according to the JavaDoc? A Class is not the same thing as a method.

  • HashMap question please

    Dear All,
    i am using in my code a hashmap< ArrayList<Byte>,String>
    and :
    Long bits = new Long(0);
    for (int i = 0; i < nodes.length; i++) {
    if (nodes.getValue() != null) {
    ArrayList<Byte> search = nodes[i].getValue();
    String s = huffmanTable.get(((ArrayList<Byte>)search));
    System.out.println(huffmanTable.values());
    System.out.println(huffmanTable.keySet());
    System.out.println("String" + s);
    System.out.println(" nodes.get(i).getValue() "+ nodes[i].getValue());
    System.out.println(huffmanTable);
    bits += (nodes[i].getFrequency() * s.length());
    These two lines :
    System.out.println(huffmanTable.values());
    System.out.println(huffmanTable.keySet());
    resulted in :
    [1100, 000, 100, 010, 1011, 011, 1010, 001, 111, 1101]
    [[3, 72], [3, 68, 32], [3, 87, 72], [2, 79, 85], [1, 32, 72], [1, 87, 82], [2, 72, 32], [1, 71, 79], [1, 65, 84], [1, 71, 84]]
    although the s was null and gave me null pointer exceptin !! which is soo wiered , i can't get why ?? or how although it contains all values + when i printed : nodes[i].getValue();
    it was = [3, 72] !!
    can any body help me as i really want to know how come the HashMap can't feel the ArrayList , even the method .contains of the HashMap gave me false !!!!
    wishing to find any help guys
    thank you in Advance.
    Regards,
    D.Roth.

    Hope the code snippet below might be of some help....
    HashMap<String,ArrayList<String>> hm = new HashMap<String,ArrayList<String>> ();
    ArrayList<String> al = new ArrayList<String>();
    al.add("java");
    al.add("solaris");
    al.add("sun");
    al.add("SDN");
    hm.put("ArrayList",al);REGARDS,
    RaHuL

  • Trouble understanding treemap question

    Okay,
    here is the question:
    Create 10,000 unique random key values in the range 10,000 to 100,000. Hold them in array key. Use Random class's nextInt(n) method to add a random offset to the last randomly value generated. Start with value 1.
    rn = rn + aRandom.nextInt(7) + 1;
    Store Data Objects in the TreeMap and HashMap. Data Objects have the following 4 fields:

    (my post was cut off)
    Create 10,000 unique random key values in the range 10,000 to 100,000. Hold them in array key. Use Random class's nextInt(n) method to add a random offset to the last randomly value generated. Start with value 1.
    rn = rn aRandom.nextInt(7) 1;
    Store Data Objects in the TreeMap and HashMap. Data Objects have the following 4 fields:
    int id; // key;
    string name; // select from 5 names with key[i] % 5
    int age; // 20 + ley % 30
    string gender; // select from "male" or "female" with key[i] % 2the random key values, key, are integers. How do you select from 5 names, that are strings, with key[i] modulus 5?

  • Doubt on hashmap

    Map qmap = new TreeMap( //some initialized Map);
    Iterator faqs = qmap.values().iterator();
    int count=1;
    Map params = new HashMap();
    while(faqs.hasNext()) {
    params.put("question" , faqs.next());
    params.put("qid" , topic + "_" + count);
    count++;
    my question is that , will this code not be wrong as the key values will not be unique in the HashMap (params)......

    That's right. After the loop you'll only have two
    keys in the HashMap: "question" and "qid".So if question and qid are related you could design a class with these two as parameters. Than you store objects of that class in an ArrayList instead.
    Or you could associate qid with question in a HashMap like
    while(faqs.hasNext()) {
       params.put(topic + "_" + count , faqs.next());
       count++;
    }That would give you unique keys. You have many options depending on what you want to accomplish.

  • Sorting TreeMap

    Hi,
    I've been trying to work this out and can't seem to find a solution. I have a treemap of object and I want to sort them by their names, such as lastname. These object hold all these datas. I wrote myself a comparator class like this:
    import java.util.*;
    import java.io.*;
    public class PatientComparator implements Comparator {
    public int compare(Object obj1, Object obj2) throws ClassCastException {
    System.out.println(obj1.getClass()); //use to see what is passing in to compare
    Patient a = (Patient)obj1;
    Patient b = (Patient)obj2;
    String nameA = a.getName();
    String nameB = b.getName();
    String firstName = nameA.substring(0,nameA.indexOf(",",0)-1);
    String lastName = nameA.substring(nameA.indexOf(",",0)+1,nameA.length()-1);
    String firstName2 = nameB.substring(0,nameB.indexOf(",",0)-1);
    String lastName2 = nameB.substring(nameB.indexOf(",",0)+1,nameB.length()-1);
    int result = 0;
    if ( !(lastName.equals(lastName2)) )
         result = lastName.compareTo(lastName2);
    else
    result = firstName.compareTo(firstName2);
    return result;
    I have to use TreeMap or HashMap right now because they both utilize the assigned key to identify object quicker. But the culprit is how do I sort this TreeMap in term of object properties(like name, age). Here is the class I implement it:
    public class DoctorsOffice {
    private String office_name;
    private int ID = 1000; //start out with id # 1000
    private SortedMap active = new TreeMap(new PatientComparator());
    //private SortedSet inactive = new TreeSet();
    * Constructor for a DoctorsOffice object.
    * @param name Name of this Dr's Office
    public DoctorsOffice (String name) {
    office_name = name;
    * Add a new patient to the office. The identification
    * number is uniquely generated and is returned when the
    * Patient object is added to the database. ID numbers
    * start at 1000 and increment by one for each new Patient
    * added.
    * @param firstName first name of this patient
    * @param lastName last name of this patient
    * @param age age of this patient
    * @return the ID number assigned to this Patient
    public int addPatient (String firstName, String lastName, int age) {
    Patient new_patient = new Patient( firstName,lastName,age );
    active.put( new Integer(ID), new_patient );
    ID++;
    return (ID - 1);
    * Remove this patient from the master database. Removed patients are
    * archived in an "inactive" database which maintains Patron
    * objects in the order in which they were removed from the master
    * database.
    * @param patientNo     Patient number assigned
    * @exception throws a NoSuchPatientException
    * if this patient does not exist
    public void removePatient (int patientNo)
    throws NoSuchPatientException {
    * Add a new medication for this patient.
    * @param patientNo     Patient number
    * @param medicationName     Name of this medication
    * @param isGeneric     True if a generic drug
    * @exception throws NoSuchPatientException if
    * this patient ID does not exist.
    public void addMedication(int patientNo, String medicationName,
         boolean isGeneric ) throws NoSuchPatientException {
    if ( active.containsKey(new Integer(patientNo)) ) {
    ((Patient)active.get(new Integer(patientNo))).recordNewMed(
    medicationName, isGeneric );
    else
         throw new NoSuchPatientException();
    * Print the medication detail for this patient. Print
    * the patient's full name (lastname COMMA SPACE firstName)
    * then each medication (each one on a new line). To print
    * the medications, simply call your toString() method in
    * the Medication class.
    * If this patient has no medication history, print "No Medications
    * Prescribed".
    * @param patientNo     Patient number
    * @exception throws NoSuchPatientException
    * if patient does not exist.
    public void printMedicationDetail (int patientNo)
         throws NoSuchPatientException {
    Integer patientID = new Integer(patientNo);
    if ( active.containsKey(patientID) ) {
    System.out.println( ( (Patient)active.get(patientID)).getName() );
    ((Patient)active.get(patientID)).printMedicationHistory();
    else
    throw new NoSuchPatientException();
    * Print all patients ordered by last name, then first name if
    * you encounter two patients with the same last name.
    * To print the Patient objects, simply call your toString() method
    * in the Patient class.
    public void listByName() {        
         // Collection coll = active.values();
    // List temp = new ArrayList(coll);
         // sort(temp,new PatientComparator());
    // Set s = temp.keySet();
    Iterator iterator = active.iterator();
    while( iterator.hasNext() ){
         // String key = (String)iterator.next();     
         System.out.println(iterator.next());     
    }

    I guess I go with the easiest way to do it. But here's
    another culprit, since values() method turn my
    TreeMap into a collection(interface), It doesn't turn the TreeMap into anything. That is, the original TM still exists, exactly as you left it. There's just a new Collection created that refers to each of the TM's values.
    and the sort()
    method is in class Collections, how do I call the
    sort(), and also the sort() method has two parameters
    (List list, Comparator C)If your values implement Comparable, and you want to use the natural sort order (for instance, the values are Strings and you just want them sorted alphabetically), then you just call the sort method that takes a single List parameter. Otherwise (for instance, you want to reverse the sort order, or sort by length, etc.), you have to write a Comparator for your values.
    >
    1st) I don't have any list to put as parameter.Both LinkedList and ArrayList take a Collection as a constructor arg, I think, so you can construct one from the Collection returned by values().
    2nd) Comparator C will keep comparing two keys from
    the treemap or in the collection?
    Collection coll = active.values();
    Collections.sort( , new
    PatientComparator());The TreeMap's Comparator will do that. The values List will sort however you tell it to, regardless of how the TreeMap sorts its keys.
    I don't think the sort is able to be called this way,
    and what do I substitute in for a parameter list when
    I have a treemap right now? Huh?

  • How to write Question paper program in jsp....

    Hi..,
    This is sure from india. I would like to develop online examination project. Everything is ok. But i have a problem at deveop of question paper. I have 10 questions in my database. I would like display those questions one by one. How can i done this job. Please any one guide me. Because, i am new to this concept.
    with regards
    sure..)-

    First you need to extract all the question from database..
    Then put all of those questions in any of collection object...
    Then set this collection object in request as attribute..
    Keep this object in request till all question are not shown(you can eliminate questions after the have been asked)..
    Code might be like this.
    HashMap result = new HashMap();
    connection = .......;
    Statement stmt=connection.createStatement();
    rs = stmt.executeQuery("Your query");
    int count=0;
    while(rs.next())
    count++;
    String question = rs.getString("colName");
    result.put(""+count,question); //( ""+count)>>>>>means converting int to String
    request.setAttribute("questions",result);
    ====================================================
    now in every JSP which is intended to display a question will have to get this result object..
    Lets assume we are about to display first question()....
    ===========================================
    //////// First get result map from request
    HashMap questions = (HashMap)request.getAttribute("questions");
    String count;
    count = request.getAttribute("count");
    if(count==null)
    count="1";
    String question = questions.get(count);
    count = new String(""+(Integer.parseInt(count).intValue()+1));
    ///Now do what you have to do with this questionresult
    questions.remove();
    request.setAttribute("count",count);////setting question no in request
    request.setAttribute("questions",questions);////setting rest of questions in request
    ===================================================
    hope this might be helpful........
    if there is any problem you can consult me anytime

  • ConcurrentSkipListMap concurrency question

    I am not much familiar with the internals of that class...
    Is it thread-safe to add entries to that map and in another thread to clone the map ?
    What about the ConcurrentHashMap ?
    Thanks.

    yes. You will get a consistent copy of the data.
    However if you add multiple entries as a group e.g. with addAll or putAll, there is no guarentee you will get all or none. You could get some of them but not all.
    Because these classes are concurrent, you may find you don't need to clone them. If you want to snapshot of the data, you are unlikely to need to update the snapshot in a multi-threaded manner so you can just copy the data to a plain TreeMap or HashMap.

  • Re: sorting TreeMap

    You can't exactly sort a TreeMap because it's order is fixed as it's built. It's maintained in order, you don't sort it.
    However you can supply a Comparitor object but it will need to define a full ordering of the keys. You could create a secondary TreeMap with a Comparitor which looked up the product code in a simple TreeMap and retrived and compared the priorities.
    I think what I'd do is to define a class to contain the fields of each record. You can then simply store these records in an ArrayList or LinkedLIst which will maintain them in the order which the database has sorted for you.
    If you want to also be able to access them by, say, product code then build a Map as you read them in to provide that as a secondary access.

    ... still i'm curious abt the TreeMap code.
    Can anyoneone send me
    the example, if possible.The following shows a TreeMap sorts Hashmap..
    import java.util.*;
    public class HashToTree {
    private java.util.HashMap hashMap;
    /** The tree map to sort data. */
    private java.util.TreeMap treeMap;
    public void demonstrate(){
    hashMap = new HashMap();
    hashMap.put("Key2", "2");
    hashMap.put("Key4", "4");
    hashMap.put("Key1", "1");
    hashMap.put("Key3", "3");
    //Sort the hash map using a tree map
    treeMap = new TreeMap(hashMap);
    public static void main(String[] args) {
    HashToTree hash_tree = new HashToTree();
    hash_tree.demonstrate();
    System.out.println("HashMap: " + hash_tree.hashMap);
    System.out.println("TreeMap: " + hash_tree.treeMap);
    }

  • Indexing XML

    Hello everyone,
    I have this situation and need some advices.
    I have an XML document, this is the part of it:
                        <s>
                        <w lemma="europietiškas" ana="#btn&#303;vvv">Europietiškasis</w>
                        <pc>,</pc>
                        <w lemma="prid&#279;tinis" ana="#btnnmvk">prid&#279;tin&#279;s</w>
                        <pc> </pc>
                        <w lemma="vert&#279;" ana="#dmvk">vert&#279;s</w>
                        <pc> </pc>
                        <w lemma="mokestis" ana="#dvvv">mokestis</w>
                        <pc>.</pc>
                        <w lemma="nebusti(-nda,-do)" ana="#vnntsv3">Nebus</w>
                        <pc> </pc>
                        <w lemma="taikyti(-o,-&#279;)" ana="#dtnnenvvv">taikomas</w>
                        <pc> </pc>
                        <w lemma="vaistas" ana="#dvdn">vaistams</w>
                        <pc> </pc>
                        <w lemma="ir" ana="#j">ir</w>
                        <pc> </pc>
                        <w lemma="spauda" ana="#dmvk">spaudos</w>
                        <pc> </pc>
                        <w lemma="leidinys" ana="#dvdn">leidiniams</w>
                        </s>tag <s> - describes a sentence,
    tag <w> - describes a word,
    tag <pc> describes a separator between words
    My question is how can I index those words from <w> tags that I will be able to search a word and get results like below:
    001.  short, possibly not the best method, I looked up WORD in the Concordance and noted that the Bible
    002.  ughter, wife, or mother, before being cultured (a WORD now bereft both socially and politically of t
    003.  ) in place of original (**f), and his revised 100 WORD basic glottochronological list in Towards Gre
    004.  ut in at Dartmouth, England, in the fall of 1609, WORD of Hudson's findings leaked out, and English
    005.  d middle course might lead to devices like a 5000-WORD alphabetized dictionary from which every fift
    006.   as a POW began. It was a word he was proud of, a WORD that meant much to him, and he used it wThis results called concordance. The XML document which I described above (just a part of it), consists of about 60 000 lines.And I have 3000 of those XML documents. . I need to build search engine. For that I need to index those XML files to get the concordance result.
    The "WORD" is the word that I'm searching. The lines in left and right side of it is the words from XML <w> tags.
    Is there any way to do this except Lucene (I tried it already, didn't work). Is there some methods of java collections, treemaps or hashmaps that I can use?
    Any help would be very appreciate.
    Edited by: peliukasss on Jun 22, 2010 10:27 AM
    Edited by: peliukasss on Jun 22, 2010 10:28 AM

    Hi, I went here to better understand what you're doing.
    My first inclination is to mention that using a database seems to make more sense, seeing the amount of data. Java 6+ comes with derby built-in, mysql is fun too.
    Second, if you did not come up with that idea (to set up a database to hold the data of your 3000 XML files) yourself, are you sure how to approach this whole concordance-thing at all? This forum works best with to-the-point questions of isolated problems and general (design) questions without too much implementation details. Asking "Is dealing with 3000 * 60000 data items in memory a good approach" might have given you an answer sooner.
    Good luck!

  • Putting items into hashmap and treemap

    Hi all, this is my first time posting here, I tried doing a search but i didn't find what i was looking for so i hope someone out there and help me out~
    Anyways, my question is that howcome when I am putting entries into either of these maps, the times for entry acutally gets faster as more entries are entered??
    For instance, in my hashMap, it took approximately 8 seconds to enter 1447 entries, but when i am entering in 23042 entries, it takes just a bit over 1 second?
    Does it have soemthing to do with how the methods in hashMap takes on constant time (O(1)) ?
    the same thing happens for HashMap, but the time cost is (O(log n)) for putting entries so i am not sure how to explain this..
    I hope someone understands my question, thanks in advance!

    8 seconds for 1400 entries sounds VERY long.
    In any case, earlier chunks may take longer due to VM startup or hotspot warmup overhead. Resizing the backing store, GC, VM acquiring more memory, OS giving CPU time to other proesses, etc., could all throw off your timing.
    I got the following results:
    HashMap:
    first 350,000: 1 s
    next 300,000: 1 s
    next 250,000: 1 s
    TreeMap:
    First 100,000: 1 s
    Next 50,000: 3 s
    Next 100, 000: 2 s
    Next 50,000: 1 s
    Next 50,000: 1 s
    and so on--generally 1 or 2 seconds per 50,000
    import java.util.*;
    public class MapTiming {
      public static void main(String[] args) throws Exception {
        Map<Integer, Integer> hm = new HashMap<Integer, Integer>();
        Map<Integer, Integer> tm = new TreeMap<Integer, Integer>();
        long start;
        start = System.currentTimeMillis();
        for (int ix = 1; ix <= 1000000; ix++) {
          hm.put(ix, ix);
          if (ix % 50000 == 0) {
            long end = System.currentTimeMillis();
            System.out.println("HashMap " + ix + ": " + ((end - start) / 1000) + " sec.");
        start = System.currentTimeMillis();
        for (int ix = 1; ix <= 1000000; ix++) {
          hm.put(ix, ix);
          if (ix % 50000 == 0) {
            long end = System.currentTimeMillis();
            System.out.println("TreeMap " + ix + ": " + ((end - start)/ 1000)+ " sec.");
    :; java -cp classes MapTiming
    HashMap 50000: 0 sec.
    HashMap 100000: 0 sec.
    HashMap 150000: 0 sec.
    HashMap 200000: 0 sec.
    HashMap 250000: 0 sec.
    HashMap 300000: 0 sec.
    HashMap 350000: 1 sec.
    HashMap 400000: 1 sec.
    HashMap 450000: 1 sec.
    HashMap 500000: 1 sec.
    HashMap 550000: 1 sec.
    HashMap 600000: 1 sec.
    HashMap 650000: 2 sec.
    HashMap 700000: 2 sec.
    HashMap 750000: 2 sec.
    HashMap 800000: 2 sec.
    HashMap 850000: 2 sec.
    HashMap 900000: 3 sec.
    HashMap 950000: 3 sec.
    HashMap 1000000: 3 sec.
    TreeMap 50000: 0 sec.
    TreeMap 100000: 1 sec.
    TreeMap 150000: 4 sec.
    TreeMap 200000: 4 sec.
    TreeMap 250000: 6 sec.
    TreeMap 300000: 7 sec.
    TreeMap 350000: 8 sec.
    TreeMap 400000: 11 sec.
    TreeMap 450000: 12 sec.
    TreeMap 500000: 14 sec.
    TreeMap 550000: 14 sec.
    TreeMap 600000: 16 sec.
    TreeMap 650000: 18 sec.
    TreeMap 700000: 19 sec.
    TreeMap 750000: 21 sec.
    TreeMap 800000: 22 sec.
    TreeMap 850000: 25 sec.
    TreeMap 900000: 25 sec.
    TreeMap 950000: 26 sec.
    TreeMap 1000000: 29 sec.

  • Array of treemap, newbie question

    Hi
    I am quite a newbie at programming (in java) so please don't be surprised if the answer to my question is extremely obvious. An answer would still be very appreciated.
    I am trying to create an array of hashmaps, below is the code that i have used:
    import java.util.TreeMap;
    * An attempt at making an array of treemaps
    * @author (your name)
    * @version (a version number or a date)
    public class DefaultCatalogue
    private TreeMap[] defaultthing;
    * Constructor for objects of class DefaultCatalogue
    public DefaultGuitars()
    defaultthing = new TreeMap[4];
    bigInitialiser();
    private void bigInitialiser()
    defaultthing[1].put("Model: ","Les Paul Standard 2004");
    defaultthing[1].put("Brand: ","Gibson");
    defaultthing[1].put("Type: ","Electric");
    defaultthing[1].put("Factoryprice: ","�1200");
    defaultthing[1].put("Retailprice: ","�1900");
    defaultthing[1].put("Stock: ","2");
    I am using bluej, and the code above compiles without giving any errors. When i try to create an object of this class, however, I get a nullpointerexception at the line
    defaultthing[1].put("Model: ","Les Paul Standard 2004");
    I have tried something similar with hashmaps, but i get the same error when i try to create an object. Could someone please tell me what im doing wrong???
    Thanx in advance

    I implemented the solution u posted and figured i
    should have added the line marked *** below in
    defaultSpecsInitialiser()
    public void defaultSpecsInitialiser()
    specs[1] = new defaultspecifications();
    ions(); <-----------***
    specs[1].defaultbridge = "tuneomatic";
    This once again compiled properly but I also got an
    error when i attempted to create an object(this
    attempt, btw, lasted more than 15 seconds...).
    This time it was an error called
    "StackOverflowError".
    The program I used, bluej, was unable to provide me
    with any details about this error.
    Help will once again be very appreciatedPlease post in your own thread to avoid confusion:http://forum.java.sun.com/thread.jspa?threadID=604035&tstart=0Moreover, you should actually read the answers you are given!

  • Use an HashMap, an TreeMap or just an array?

    Hi,
    i have a fixed size of graph nodes, lets say 100.000.
    Each of these nodes should have an own id, where i just would take the node number - if i increment on these nodes - as such an id.
    Suggestion a)
    If i safe them to an HashMap, the key is the id as
    nodeCounter = 0;
    HashMap h = new HashMap(100.000);
    h.put(new Integer(nodeCounter++), nodeInstance);
    //...put in  all nodes-> To search for a node would be constant time O(1)
    -> What about insertion, also O(1)?
    Suggestion b)
    if i safe it to a TreeMap i would have also the key as the id and put in all
    the nodes. Since the key is just an unique Integer from 1-100.000 a
    comparator can be used to keep the RedBlackTree sorted.
    -> To search for a node would cost O(log(n))
    -> To insert a node would cost O(log(n))
    Suggestion c)
    Since a node is just represented on screen by his id and a fixed String as Node"+"1" -> "Node 1" i thought of using an simple array to safe the nodes, since each index of the array is just the id of the node.
    -> To find a node costs O(1)
    -> To insert a node is dynamically not possible
    My preferring suggestion is a)
    but only if the insertion an finding of an node is both constant O(1).
    Is it an advantage for a TreeMap to keep
    the elements sorted, compared to a HashMap which keeps them unordered?
    What do you think?
    Do you have any good advice for me or any other good alternative how to solve this problem? By reaching best performance?
    Thanks a lot for your answer!
    Message was edited by:
    Cinimood

    ok, thanks for your answer - i will describe the whole problem i want to solve:
    given is an undirected graph of nodes, let�s say a network graph.
    This graph contains about 1000 nodes(less or 2000 or 3000 is also possible), where the nodes are linked by each other -
    could be a full mesh in the worst case. Each link is assigned a weight.
    The features this graph should provide are:
    - adding a node when the graph is already created i.e. represented by the datastructure.
    - searching for a link between two nodes
    To represent a graph by a datastructure is best by using an adjacency matrix or an adjacency list.
    Searching for a link between two nodes the adjancency matrix provides best performance by just O(1). But the adjacency
    matrix needs memory by O((n^2)/2) -> divided by 2, because the graph is undirected, O(n^2) in a directed graph.
    ok, using an array like:
    Node nodes[] = new Nodes[1000]; is of course best to retreive each node by just his id which is equivalent to his index -> node[1] has id 1.
    but if i�m using an array, i cannot add another node dynamically.
    (Note: I need Node instances because each node holds its x and y coords for displaying, which is not important
    now.)
    Now, i think of a solution like this - with focus on adjacency matrix and HashMap without regarding adjacency list:
    use an adjacency matrix for searching for the specific link between two nodes because of the good performance of O(1). Because the graph is undirected i only need the upper(or lower) part of the diagonal of the matrix,
    thus O((n^2)/2) memory.
    use a HashMap for the nodes, where the key of the node entry for the HashMap is just his ID:nodeMap.put(new Integer(nodeCounter++), nodeInstance);use a HashMap for the links between the nodes, where a link is represented by the class Link which holds just the weight.
    To identify the link, use an ID which consists of the concatenation row+column of the adjacency matrix e.g.
    row = 1, column = 2 -> ID = 12
    linkMap.put(new Integer(row+column), new Link(weight));-> if i want to insert a weighted link between node 2 and node 5 i just modify the Link object in the linkMap which has the
    key 2+5 -> 25.
    That�s what i want to do and what makes me thinking all the time of good performance,
    because a lot of nodes might exist and searching, deleting and inserting must be quick.

  • HashMap or Treemap Help needed

    Hi all.
    I have posted some code up in java programming but so far the returns i have been given are to comlicated for me to understand. I am only a novice at java, and i have been given an assignment which involves connecting multiple clients to a server. This part of the assignment has been completed with no hassles. The part I am stuck at is I need to create a list of online users everytime a client logs on. The problem is i create a new thread which gets handled in anotherclass from my server Class called SocketHandler. Because each time a client logs on a new instance of socketHandler is created for that client, i can't establish a proper list of online users.
    Now i have been told that I can achieve what i am after by using a hashmap or treemap, but what some ppl have posted back if far to complex for me.
    I have posted my code below for an example of what i am after.
    Hopefully someone can help.
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class Server/
         Socket socket = null;
         ServerSocket serverSocket = null;
         public static void main(String args[])
              Server server = new Server();
              server.createSocket();
         public void createSocket()
              try
                   serverSocket = new ServerSocket(10000);
                   System.out.println("Waiting for client connections...");
                   System.out.println("");
              catch(IOException e)
                   System.out.println("Port in use... Exiting");
                   System.exit(0);
              while(true)
                   try
                        socket = serverSocket.accept();
                        System.out.println("New connection accepted " + socket.getInetAddress() + ":" + socket.getPort());
                        System.out.println("waiting...");
                        System.out.println();
                        list.add(socket.getInetAddress() + ":" + socket.getPort());
                        System.out.println(list);
                   catch(IOException e)
                        System.out.println(e.getMessage());
                   Thread thread = new Thread(new SocketHandler(socket));
                   thread.start();
    class SocketHandler extends Server implements Runnable
         int count = 0, attempt = 0;
         BufferedReader reader, auth;
         PrintWriter writer;
         Socket incoming = null;
         SocketHandler(Socket socket)
              this.incoming = socket;
         public void run()
              try
    }

    Now i have been told that I can achieve what i am
    after by using a hashmap or treemap, but what some
    ppl have posted back if far to complex for me.Then you should ask those people to explain it differently.
    Start here.
    http://java.sun.com/docs/books/tutorial/collections/

Maybe you are looking for

  • Apple remote desktop not working

    Just upgraded to Mavericks and can not use apple remote desktop.  I bought my copy of ARD from the store.  Anyway of getting this fixed?

  • Please help? Itunes will not open with Windows 7.

    I have tried everything in the posts, etc and still can't get it to work. Any ideas? I'm not the most computer literate person so need pretty simple instructions.

  • Export and then import those images in one step?

    I'm slightly annoyed that every time I want to use the export function to create jpeg versions of images, I then have to do the extra step of importing those jpegs into my catalog. Is there some way to do this in one step? If I need .tiff's of .psd's

  • Configure reports with tomcat

    hi, i wanted to know know how can i integrate apache tomcat 5.0 with oracle reports. so that when i run apache as my http server and type a request for report on the URL it interprets and shows me the report. what steps should i perfrom, kindly elabo

  • 256 gb ssd vs 500gb hhd

    HAD TO REPLACE THE HD IN MY 2011 IMAC, HAD ISSUES WITH THE NEW HD SO THE **** WITH IT I WANTED A SSD ANYWAY. SINCE I ONLY USE ABOUT 16 GB AT ANY GIVEN TIME WOULD I STILL BENNEFIT ISTALLING A 256 GB PRO SSD .