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.

Similar Messages

  • 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/

  • I wanna use a HashMap instead of an array..but how ??

    Here's the class I'm using...
    public class Group {
         private Student[] list;
         public final int GROUPE_SIZE;
         private float[] finalGrades;
         public Group(int size) {
              GROUPE_SIZE = size;
              list = new Student[size];
         public void addStudents(Student[] list) {
                   this.list = list;
         public Student[] getList(){
              return list;
         public void setFinalGrades() {
              finalGrades = new float[GROUPE_SIZE];
              for (int i = 0; i < GROUPE_SIZE; i++) {
              finalGrades[i] = list.getFinalGrade();
              Arrays.sort(finalGrades);
         public float getLowestGrade() {
              return finalGrades[0];
         public float getHighestGrade() {
              return finalGrades[GROUPE_SIZE-1];
         public float getAverage() {
              float total=0.0f;
              for (int i=0; i < GROUPE_SIZE; i++) {
                   total+= finalGrades[i];
              return total/GROUPE_SIZE;

    I have to replace all the arrays in this class by using the HashMap, but I don't know how
    In order to know how, you need to know why.
    It looks like your class provides grades for students. Now, a Map (of which HashMap is an implementation) provides for mapping from one object to another. In your case, you probably want to look up students' grades, so your mapping would be "student-->grade"
    Read the collections examples linked above and you should be well on your way - but just remember that you need to know the "why" before the "how," otherwise you'll end up in a mess. Understand what it is you're trying to do, what the need is that your code satisfies.

  • How to Capitalize the first letter or an entire word using a shortcut on the keyboard just like in microsoft that uses shift+F3

    please how can one How to Capitalize the first letter or an entire word using a shortcut on the keyboard just like in microsoft that uses shift+F3

    What do you mean there was "no effect?" I'm not aware of any effects.
    It looks like that Service is also in the App Store. From their screen shots, the services are prefaced with WordService:
    You can see an example in the App Store for their app: App Store
    After installing, you should now have those text services in your Services menu. You can then add shortcuts in the Keyboard System Prefs.
    Most Apple apps have a Transformations menu in the Edit menu. You can Make upper, lower, and Initial caps with those. I would stick with Word Services, but you can make Application Shortcuts for the items in the Transformations menu.
    Again, in Keyboard System Prefs, Under Applications, Click the Add button on the right side pane.
    Set it for All Applications
    Enter the menu command exactly as they appear in the Transformation menu (separate entries for each),
    Make Upper Case
    Make Lower Case
    Capitalize
    Give them a shortcut.

  • HT1349 How do I set up a speed dial on my iPhone 4s?  I am used to the bberry where I just keep my finger on a number in order to dial. This is very useful in the car.  How do I get the same effect on iPhone?

    How do I set up a speed dial on my iPhone 4s?  I am used to the bberry where I just keep my finger on a number in order to dial. This is very useful in the car.  How do I get the same effect on iPhone?

    I found a post from Alope that told me exactly how to fix it.
    Go to:
    Settings   - General   - Restrictions    -    put your pass code in   -     Facetime      -  turn the switch to ON
    Worked perfectly to stop the message that said, Not authorized to do that!

  • I can't get yahoo to open using firefox or safari.  I just installed updates...then the problems began.  gmail is working fine

    I can't get yahoomail to open using foxfire or safari.  I just installed updates then the problem began.  Gmail is working fine

    What happens when you try?

  • Acrobat X Pro hangs when making PDF. Using on Windows 7 64. Just started hanging. Uninstalled and reinstalled. Installed update. Once it hangs, must go into crtl, alt, delete to force close.

    Acrobat X Pro hangs when making PDF. Using on Windows 7 64. Just started hanging. Uninstalled and reinstalled. Installed update. Once it hangs, must go into crtl, alt, delete to force close.

    As a debugging step, try printing to the Adobe PDF printer. If that fails, repeat with print-to-file selected. Assuming the print succeeds, open the file in Distiller to complete the creation of the PDF. If you get the PDF, then check to see if AcroTray is properly working as a background task.

  • I bought my i pod touch from us but i live in india .i have been using this from many days fr just a few days before something went wrong with it and the date and time has changed what do i do?

    i bought my i pod touch from us but i live in india .i have been using this from many days fr just a few days before something went wrong with it and the date and time has changed what do i do?

    Have you went to Settings>General Time&Date and correct the time.  Make sure the time zone is correct too.  Also go to Settings>General>Inernational and make sure the Gergorian calender is selected.

  • Google Maps dowloaded, but don't know how to use it or find what I just downloaded?

    just bought a blackberry curve and know nothing about it. I went to google maps and clicked download, and it finished downloading and now I do not know how to use google maps or find where it is on my phone. How do I find where it is on my phone? (When I finished downloading it asked if I wanted to "run" or something else, I checked the other box - Also, if I go back to google and try to download google maps again it says it was already downloaded on my phone!)
    I do know how to use google maps on a computer, just not on my phone.

    Assuming that it downloaded and installed ok on your Curve, the first step is to find the application icon.  Depending on your theme you're using, you may need to press the menu button to display the full list of applications. Do that by pressing the button to the right of the trackball (with the dots). 
    The google maps icon is kind of orange and looks like a little folded map. After you click on that, it's pretty straight forward. Click on the menu button to search for a location and get directions.
    Hope that's not too basic of instructions.  Besides from email, google maps is the thing I use the most.  Verizon cripples the GPS, but the approximate location based on cell towers is still super useful.  Enjoy!

  • I can't find film on my Ipad that I paid for on rental. I am using iOS 8.1 which I just downloaded. I cant find a rental tab in my Video App

    I can't find film on my Ipad that I paid for on rental from ITune.  I am using iOS 8.1 which I just downloaded. I cant find a rental tab in my Video App

    Clear Safari, then force close Safari and finally reset your iPad.
    Go to Settings>Safari>Clear History and Website Data
    Now close Safari. In order to close apps, you have to drag the app up from the multitasking display. Double tap the home button and you will see apps lined up going left to right across the screen. Swipe to get to the app that you want to close and then swipe "up" on the app preview thumbnail to close it.
    Next, reset the iPad by holding down on the sleep and home buttons at the same time for about 10-15 seconds until the Apple Logo appears - ignore the red slider if it appears on the screen - let go of the buttons. Let the iPad start up.

  • HT1695 My new iPad with Retina Display is not able to connect to the Wi-Fi of my new Time Capsule. It used to connect, but now it just spins and spins and never connects. I've tried rebooting everything many times.

    My new iPad with Retina Display is not able to connect to the Wi-Fi of my new Time Capsule. It use to connect, but now it just spins and spins and never connects. I've tried rebooting everything many times.

    Some things to try first:
    1. Turn Off your iPad. Then turn Off (disconnect power cord for 30 seconds or longer) the wireless router & then back On. Now boot your iPad. Hopefully it will see the WiFi.
    2. Go to Settings>Wi-Fi and turn Off. Then while at Settings>Wi-Fi, turn back On and chose a Network.
    3. Change the channel on your wireless router (Auto or Channel 6 is best). Instructions at http://macintoshhowto.com/advanced/how-to-get-a-good-range-on-your-wireless-netw ork.html
    4. Go into your router security settings and change from WEP to WPA with AES.
    5.  Renew IP Address: (especially if you are droping internet connection)
        •    Launch Settings app
        •    Tap on Wi-Fi
        •    Tap on the blue arrow of the Wi-Fi network that you connect to from the list
        •    In the window that opens, tap on the Renew Lease button
    ~~~~~~~~~~~~~~~~~~~~~~~~~
    iOS 6 Wifi Problems/Fixes
    How To: Workaround iPad Wi-Fi Issues
    http://www.theipadfan.com/workaround-ipad-wifi-issues/
    Another Fix For iOS 6 WiFi Problems
    http://tabletcrunch.com/2012/10/27/fix-ios-6-wifi-problems-ssid/
    Wifi Doesn't Connect After Waking From Sleep - Sometimes increasing screen brightness prevents the failure to reconnect after waking from sleep. According to Apple, “If brightness is at lowest level, increase it by moving the slider to the right and set auto brightness to off.”
    Fix For iOS 6 WiFi Problems?
    http://tabletcrunch.com/2012/09/27/fix-ios-6-wifi-problems/
    Did iOS 6 Screw Your Wi-Fi? Here’s How to Fix It
    http://gizmodo.com/5944761/does-ios-6-have-a-wi+fi-bug
    How To Fix Wi-Fi Connectivity Issue After Upgrading To iOS 6
    http://www.iphonehacks.com/2012/09/fix-wi-fi-connectivity-issue-after-upgrading- to-ios-6.html
    iOS 6 iPad 3 wi-fi "connection fix" for netgear router
    http://www.youtube.com/watch?v=XsWS4ha-dn0
    Apple's iOS 6 Wi-Fi problems
    http://www.zdnet.com/apples-ios-6-wi-fi-problems-linger-on-7000004799/
    ~~~~~~~~~~~~~~~~~~~~~~~
    How to Fix a Poor Wi-Fi Signal on Your iPad
    http://ipad.about.com/od/iPad_Troubleshooting/a/How-To-Fix-A-Poor-Wi-Fi-Signal-O n-Your-iPad.htm
    iOS Troubleshooting Wi-Fi networks and connections  http://support.apple.com/kb/TS1398
    iPad: Issues connecting to Wi-Fi networks  http://support.apple.com/kb/ts3304
    WiFi Connecting/Troubleshooting http://www.apple.com/support/ipad/wifi/
    How to Fix: My iPad Won't Connect to WiFi
    http://ipad.about.com/od/iPad_Troubleshooting/ss/How-To-Fix-My-Ipad-Wont-Connect -To-Wi-Fi.htm
    iOS: Connecting to the Internet http://support.apple.com/kb/HT1695
    iOS: Recommended settings for Wi-Fi routers and access points  http://support.apple.com/kb/HT4199
    How to Quickly Fix iPad 3 Wi-Fi Reception Problems
    http://osxdaily.com/2012/03/21/fix-new-ipad-3-wi-fi-reception-problems/
    iPad Wi-Fi Problems: Comprehensive List of Fixes
    http://appletoolbox.com/2010/04/ipad-wi-fi-problems-comprehensive-list-of-fixes/
    Connect iPad to Wi-Fi (with troubleshooting info)
    http://thehowto.wikidot.com/wifi-connect-ipad
    Fix iPad Wifi Connection and Signal Issues  http://www.youtube.com/watch?v=uwWtIG5jUxE
    Fix Slow WiFi Issue https://discussions.apple.com/thread/2398063?start=60&tstart=0
    How To Fix iPhone, iPad, iPod Touch Wi-Fi Connectivity Issue http://tinyurl.com/7nvxbmz
    Unable to Connect After iOS Update - saw this solution on another post.
    https://discussions.apple.com/thread/4010130
    Note - When troubleshooting wifi connection problems, don't hold your iPad by hand. There have been a few reports that holding the iPad by hand, seems to attenuate the wifi signal.
    ~~~~~~~~~~~~~~~
    If any of the above solutions work, please post back what solved your problem. It will help others with the same problem.
     Cheers, Tom

  • HT4865 How secure are my personal emails and chats using the iCloud if my daughter just synced all our family apple devices to the cloud?

    How secure are my personal emails and chats using the iCloud if my daughter just synced all our family apple devices to the cloud?

    Welcome to the Apple Community.
    http://support.apple.com/kb/HT4865

  • I am using Aperture 3 and I have just exported the edited picture to my desktop but the image which is now on my desktop appears to be unedited. Does anyone know why??

    I am using Aperture 3 and I have just exported the edited picture to my desktop but the image which is now on my desktop appears to be unedited. Does anyone know why??

    Did you export the master or version? Master will be unedited...
    File > Export > Version

  • I am using Adobe Photshop Elements 11, I just transferred all of my data from an old computer to a new computer, all my pictures and documents transferred fine but, my albums are missing and the date and time that is usually under the picture are missing.

    I am using Adobe Photoshop Elements 11, I just transferred all of my data from an old computer to a new computer, all my pictures and documents transferred fine but, my albums are missing and the date and time that is usually under the picture are missing.. How do I get them back?

    Hi,
    Which operating system are you running on?
    The date & Time can be displayed by going to the View menu and checking Details - also File Names if you want them displayed.
    The Album information is saved within the catalog so it sounds as though you didn't do a catalog backup on the old computer and a catalog restore on the new computer which is the recommended way of transferring elements data. Did you just copy the photos over?
    Brian

  • ICloud not allow login. It shows the password error but I am able to login to site using same Apple ID. I just update my software to Mountain Lion 10.8.2

    iCloud not allow login.
    It shows the password error but I am able to login to site using same Apple ID.
    I just update my software to Mountain Lion 10.8.2
    I tried a lot...
    1) I changed passwords few time. (through using forgot password options)
    2) Cleaned-up memmory and cash using ccleaner.
    3) Restarted the system couple of time, Try to login from preferance>iCloud> ...

    Or here:
    http://support.apple.com/kb/DL1611

Maybe you are looking for

  • How to save picture from an iPad on someone else computer

    how to save picture from an iPad on someone else computer.

  • SOLUTION for Time Capsule not connecting

    After 2 days of apple support we have gotten to the bottom of what I hope is the same problem most of you are having. ISSUE: Time machine is no longer backing up suddenly and the mac will not connect to the TC disk.  (Disk not found, server not avail

  • Activation Failure for Creative Suite 5.5 Web Premium Subscription

    Hi, Signed up for the subscription model a week ago and worked fine without issue; came in to work on Monday and was asked to activate photoshop; it failed but let me continue. Tried loading up photoshop again today but now it says can't continue wit

  • How to turn path back to stroke?

    i have a line art drawing and have expanded the strokes to paths. now i'd need to turn part of the paths back to strokes and can't find an (easy) way to do it. inserted is an example of the situation. instead of closed path i'd like the form to be a

  • CCMS Monitor for SMTP-Service via ICM SMTP-Plugin

    Dear all, we configured our SAP System for sending emails with the help of transaction SCOT. We are using the SMTP-Plugin brought in by the ICM. Everything works fine. Now we want to report how many emails are sent through that connection. For that w