Iterators in a TreeMap

I'm having difficulty implimenting a iterator in a TreeMap,
private TreeMap phraseIndex;
private TreeMap wordIndex;     
private Iterator phraseIndexIterator = phraseIndex.Iterator;
private Iterator wordIndexIterator = phraseIndex.Iterator;
I'm using codeWarrior, which tells me I should be able to define an iterator like that, but when I try to complile I get the following error:
No variable Iterator defined in class java.util.Treemap
Any Ideas?
Thanks in advace
Division

maybe try something like this?
//TreeMap map;
Set keyset = map.keySet( );
Iterator keys = keyset.iterator( );
while (keys.hasNext( )){
     String key = (String)keys.next( );

Similar Messages

  • Questions on ADF View Objects, Links and Iterators

    I have a number of questions regarding using ViewObjects in applications where there are alot of relationships between tables.
    First, lets say that I have ViewObject SomeView that was added to the App Module (AM) as VO1. And because it has a number of "detail" records that have to be iterated through in a "report like" view it has those other VO's added under it as "children" in the AM.
    So I have
    VO1 (an instance of SomeView)
    --> VO2 (an instance of some other view)
    --> VO3 (an instance of some other view)
    that is used on pages where only a single VO1 is shown at a time.
    Now because I had another page I wanted to make that had a listing of all SomeView objects. Some of the fields in SomeView are foreign keys to records in VO2 and VO3 and while I don't want to show all the fields from VO2 and VO3, I do want to show a name field from each rather than just the foreign key.
    My experience (though I've never read this anywhere) tells me that when doing a "table" that is a list of rows from a VO, you can't display info from the child VO's because the child VO's are on whatever record corresponds to the "currentRow" in the parent VO and just displaying the rows in a rangeSet doesn't make each the "currentRow" so even we display 10 records in a for loop, the "currentRow" is just one, and the child VO's iterators aren't moved as we go through the for loop. (Can someone confirm if I am correct on this conclusion????)
    So the only way I know of to show some field from a related table in each row is to make the VO have the entity objects from the related tables be part of the view as references. Is this the only way?
    If I do that on a view that didn't have other views as children defined in the AM I don't have any problem and it works like I want.
    But if I do it on a view that did have other views as children defined in the AM it makes the page(s) using that view with the children iterators behave badly. Half the information quits showing up, etc.
    For example, ... if I go to the "SomeView" which was defined with only one entity object association, and I add the entity objects (that are the basis of instances of VO2 and VO3 ) as referenceable only, it totally breaks the page where I display a single VO1 and use it's VO2 and VO3 children. IS THIS NORMAL OR AM I MISSING SOMETHING?
    So, is the solution that I have to have more view objects defined for different purposes ?
    Can anyone give any general guidelines for when/where to use different view objects vs. when to use different iterators. I'm not having much luck with using secondary RSI's and haven't found much info on them.
    Also, how about issues of naming iterators that are in various binding containers (ie. UI Model for a page). If I do and LOV it creates an iterator and gives it a default name like ViewNameIterator1. If I already have a different page that uses a regular (non LOV) iterator with that name, and the user goes back and forth between those pages, is that a clash?
    Finally, I've read a couple of Steve Muench's blogs on View Link consistency but I'm not sure what the rules are on when it applies and doesn't. How you turn it on or off, etc. One of his examples in http://radio.weblogs.com/0118231/2004/02/27.html talks about it in the context of two view objects that are NOT typically "linked" in a master/detail kind of way. Like an AllDepartments and a DepartmentsLessThan view. Do you have to create a View Link between them to have results of one be reflected in the other if they aren't used in the same page in a web app? Or does it happen automatically (with the caveat that you have to do the rowQualifies method). Just feels like I'm missing some pieces.
    Thanks in advance,
    Lynn

    Hi,
    I am also interested in a best-practice note from oracle.
    Currently we store history in seperate history tables for columns that changed. All this implemented in our BaseEoImpl overriding the EntityImpl.prepareForDML().
    Thanks

  • Extract values from an object trapped in TreeMap

    I can't figure out how to get the balance of an account Object (consisting of name plus balance)which is stored in a TreeMap.
    Normally it would go like this: For example
    accounts[2].getBalance();
    Normally would return the value for the specified account.
    Can anybody help?
    Thanks.
    import java.util.*;
    class Account
        private double theBalance    = 0.00;   // Balance of account
        private String theName       = "";
    public static void main (String args[]) {
                    Account accounts[] = new Account[4];
      TreeMap  accountsMap = new TreeMap();
      accountsMap.put( "0023", new Account( "Gordon", 100.0 ) );
      accountsMap.put( "0123", new Account( "James",  200.0 ) );
      accountsMap.put( "0001", new Account( "Edward", 300.0 ) );
      accountsMap.put( "7777", new Account( "Percy",  400.0 ) );
      BankStats  bs = new BankStats();
      LinkedList  r  = bs.accountsBelow( accountsMap, 250.0 );
      System.out.println(r);
        public Account( String name, double openingBalance )
          theBalance = openingBalance;
          theName    = name;
        public double getBalance()
          // assert theBalance >= 0.00;
          return theBalance;
        public String getName()
          return theName;
        public double withdraw( final double money )
          // assert theBalance >= 0.00;
          if ( theBalance >= money  )
            theBalance = theBalance - money;
            return money;
          } else {
            return 0.00;
        public void deposit( final double money )
          // assert theBalance >= 0.00;
          theBalance = theBalance + money;
    class BankStats {
          public LinkedList accountsBelow (TreeMap accountsMap, double ammount) {
               LinkedList list1 = new LinkedList();     
             for (int i = 0; i < 10000; ++i) {    
               String no = Integer.toString(i);
               for (int z =0; no.length()<4 ; z++) {
                    no= "0"+no;              
                if (accountsMap.get(no)!= null) { 
                System.out.println   (accountsMap.get(no));  // WANT TO GET THE BALANCE FOR THE ACC       OBJECT ASSOCIATED WITH THIS KEY (String no)
               if (accountsMap.get(no)< ammount) {
                                 list1.add(accountsMap.get(no)); }
          return list1;}
          public LinkedList accountsBelowNotFrozen (Account accounts[], double ammount) {
               LinkedList list2 = new LinkedList();     
             for (int i = 0; i < accounts.length; ++i) {    
               String nam = accounts.getName();
    if (accounts[i] != null) {       
    if (accounts[i].getBalance() < ammount & !nam.endsWith("[Frozen]")) {
              list2.add(accounts[i]); } } }
         return list2;}

    Use this method call to retrieve the balance (or anything else):
    Account acc = (Account) accountsMap.get(no)
    double bal = acc.getBalance();or simply:
    double bal = ((Account) accountsMap.get(no)).getBalance();

  • Two Iterators on the Same Collection

    I posted this one on the Java Collections Framework forum but there don't seem to be many people there so let me post this here, too.
    I want to use two iterators at the same time on a single collection. They are like two trains going one after another. If I use the iterator supplied by Java, however, if one iterator structurally modifies the underlying collection, the other throws ConcurrentModificationException.I want to avoid this. I want both iterators to modify the underlying collection freely, and when the collection was modified by one, I want the other to know what happened and what to do, rather than throwing an exception. How can I do this? Can I just manipulate somewhat on the Java iterator, or must I make an iterator implementation that does what I want from the scratch?

    I'm writing a flow analysis module of a compiler. I'm not totally sure what optimizer does, but it needs to manipulate the list of instructions, which involves removing and adding instructions into the list. Some time we may need two iterators that cooperate together to find out when we can remove an instruction, for example. Or, one iterator does the analysis and removal, while the other may do some cleanup work. (I say again I'm not totally sure what optimizer does.) Some guy suggested using visitor pattern, but after some investigation (of the visitor pattern stuff) I thought iterator that behaved more smartly was more relevant. Or maybe not.

  • How can I Cache the data I'm reading from a collection of text files in a directory using a TreeMap?

    How can I Cache the data I'm reading from a collection of text files in a directory using a TreeMap? Currently my program reads the data from several text files in a directory and the saves that information in a text file called output.txt. I would like to cache this data in order to use it later. How can I do this using the TreeMap Class? These are the keys,values: TreeMap The data I'd like to Cache is (date from the file, time of the file, current time).
    import java.io.*;
    public class CacheData {
      public static void main(String[] args) throws IOException {
      String target_dir = "C:\\Files";
      String output = "C:\\Files\output.txt";
      File dir = new File(target_dir);
      File[] files = dir.listFiles();
      // open the Printwriter before your loop
      PrintWriter outputStream = new PrintWriter(output);
      for (File textfiles : files) {
      if (textfiles.isFile() && textfiles.getName().endsWith(".txt")) {
      BufferedReader inputStream = null;
      // close the outputstream after the loop
      outputStream.close();
      try {
      inputStream = new BufferedReader(new FileReader(textfiles));
      String line;
      while ((line = inputStream.readLine()) != null) {
      System.out.println(line);
      // Write Content
      outputStream.println(line);
      } finally {
      if (inputStream != null) {
      inputStream.close();

    How can I Cache the data I'm reading from a collection of text files in a directory using a TreeMap? Currently my program reads the data from several text files in a directory and the saves that information in a text file called output.txt. I would like to cache this data in order to use it later. How can I do this using the TreeMap Class?
    I don't understand your question.
    If you don't know how to use TreeMap why do you think a TreeMap is the correct solution for what you want to do?
    If you are just asking how to use TreeMap then there are PLENTY of tutorials on the internet and the Java API provides the methods that area available.
    TreeMap (Java Platform SE 7 )
    Are you sure you want a map and not a tree instead?
    https://docs.oracle.com/javase/tutorial/uiswing/components/tree.html

  • Fail-fast iterators

    Hi,
    I am writing a Thread that necessarily has to iterate through the values stored in Hashtable. This Hashtable can also have elements added and removed from it concurrently while the Thread is running.
    The Thread itself will only run about once every 5 minutes and it is used to remove stale entries from the table.
    What I am currently doing is getting a Collection view of the Hashtable and then using an iterator to iterate through it.
    Collection col = table.values();
    for(Iterator itor = col.iterator(); itor.hasNext(); )
        try
            TableEntry te = (TableEntry) itor.next();
            if(System.getTimeMillis() - te.timestamp > this.ttl)
                itor.remove();
        catch(ConcurrentModificationException e)
            //the iterator has failed fast
        catch(NullPointerException e)
            //will I even get an NPE if the Iterator doesn't fail fast?
    }The API says that the fail-fast property of a Collections iterator should not be relied upon to guarantee program correctness.
    I do not particularly care if items are added to the Hashtable while the cleaning Thread is running, they won't be stale entries anyway. I assume that an Iterator created before anything is added will 'skip' over the added values if it doesn't fail-fast, is this the case? (I am well aware of the dangers of assuming, that's why I'm also asking:) )
    What I do care about is entries that are removed concurrently with the cleaning Thread. If the Iterator does not fail-fast will it return null when I call itor.next() if the value that should be returned has been removed?
    Also I would like to be able to continue processing the 'collection' of entries as it was before the Iterator failed-fast (obviously skipping any new entries or removed entries). If I catch the ConcurrentModificationException but don't break out of the loop will a ConcurrentModificationException be thrown for every subsequent interation of the loop?
    The tutorials that I have read all seem to assume that nothing will go wrong when working with Iterators...

    Thanks for the replies.
    I am implementing a part of a distributed system here.
    The Hashtable is used to store results that have been computed (by another Thread) until the process that requested the processing be done fetches them (they are removed from the table when they are fetched).
    Ideally I could just assume that everything that requests processing will be good enough to fetch the results but I know that I can't, so I figured having a Thread that slept for about 5 minutes at a time and when it woke up cleaned any stale entries would be a good thing.
    Because of this I imagine very few elements would expire, it is only going to happen when other programmers forget to fetch the results, or if the network was to go down badly, this is why I only envisage running the cleaner Thread very rarely (once every 5 minutes would be a lower bound)
    I chose Hashtable because of the way that it is synchronized. Since a new Thread is created for every processing request it is possible for a number of Threads to all be trying to access the table at the same time. I have looked at LinkedHashMap, and while it will be able to iterate through it faster, concurrent accesses would be slower (since I'd have to wrap it in a SynchronizedMap). Given that iterating through it is rare, I am not too concerned if a Hashtable is marginally slower.
    Seeing as my iterator would be toast once a ConcurrentModificationException is thrown is there any way I can completely lock the table while the cleanup Thread is running?
    AFAIK synchronizing on the table before the loop won't make the loop a critical section, it will just mutex the table object. Is there any way to define a critical section based on a mutex (very C/C++ style thinking, I know) such that I could prevent concurrent accesses to the table until the cleanup Thread has finished it's loop?
    I appreciate your help
    -Gordon

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

  • TreeMap class and message not understood issues - help please

    Can anyone help with this one please?
    The code is the start of a Map interface/TreeMap class to hold names as keys and addresses as values (both Strings).
    I think the instance variable and the constructor are correct, but the addAddress method throws an error
    Semantic error: Message addAddress( java.lang.String, java.lang.String ) not understood by class'java.util.TreeMap'.
    I can only guess that I've overlooked something quite simple? The line at the end of the code should read
    "Replaced "old address" with "new address" for "new name" and this should only display if the key already exists in the Map,
    hence the if statement. The keys and values have been declared as Objects for future flexibility. Sorry if this is all blatantly obvious.
    Also if I wanted to test this code and create an instance of the Addressbook class, what should my code look like?
    Many thanks.
    {code}import java.util.*;
    public class Addressbook
    private static Map<Object, Object> addresses;
    public Addressbook()
    super();
    this.addresses = new TreeMap<Object, Object>();
    public static void addAddress(String name, String address)
    if (addresses.containsKey(name))
    addresses.put(name, address);
    System.out.println("Replacing " + addresses.remove(name) + " with "
    + addresses.get(name) + " for " + name);
    else
    addresses.put(name, address);
    {code}

    If you're only going to store Strings in the Map, make sure you are specifying them as generics so that all operations return Strings by default.
    You don't need to use contains if you are going to replace a map value. The old value will be returned when you place the new one in. Should be quicker, since you're not searching for the same key twice.
    Do not refer to a static variable with this. it become confusing and could result in bugs. That said use static sparingly.
    The AddressBook should probably be an instance and all the variables and methods should be instance variable and methods.
    I don't know your requirements however so I'll leave this as a suggestion.
    import java.util.*;
    public class AddressBook {
       private static Map<String, String> addresses = new TreeMap<String, String>();
       public static void addAddress(String name, String address) {
          String oldAddress = addresses.put(name, address);
          if(oldAddress != null) {
                System.out.printf("Replacing %s with %s for %s%n", oldAddress, address, name);
        public static void main(String[] args) {
            addAddress("me", "123");
            addAddress("me", "321");
    }Brushfire,

  • Need Help converting objects in a TreeMap to String

    This app counts the number of times a word occurs in a document. I used a HashMap to store the key and value. The I sorted them using TreeMap. Now I need to return the key (String) and value (Integer Object) so they may be print like this -- 'key: value'.
    Example:
    that: 3
    This mean the word 'that' appeared 3 times in the document. Below is my toString() method. TreeMap sorts everything for me but I cant return 'map' because it is not a String. So I iterated through each key and value in the map. But now I dont know how to put all the iterations into 1 String value. I would greatly appreciate any help. Code below.
    Thanks in advance.
    public String toString() {
    Object key = null;
    Object value = null;
    map = new TreeMap(map);
    Set getKeys = map.keySet();
    Iterator iterKeys = getKeys.iterator();
    while (iterKeys.hasNext()) {
    key = (String)iterKeys.next();
    value = map.get(key))
    return; // i need to return a String here
    } // end toString()
    } // end class

    I dont remember posting to the "new Java forum", but I might have. My browser locked up on me so I am not sure what happened. If I did please excuse my double post.
    Are you familar with a way to solve my problem?

  • Synchronizing Iterators for master view with multiple detail - how to ?

    New to JDeveloper (from Forms) and after an introduction a week or so back, one question I have not yet answered with the ADF framework is how to synchronize iterators. Maybe I missed something simple, but if I have master table A with FK relations from detail tables B and C expressed as view objects and view links in the Model tier, when I package these up into the Application Module / Data Controls it seems I have 2 iterators for table A - one for it and it's detail set B, and another for it and it's detail set C.
    So then, if I drag & drop one of the A data controls onto a page (say from the A-B link) as a read-only-table, my PPR actions from this table work on components derived from this same data control hierarchy - ie: on detail B. But to effect a change in the other detail relationship A-C, and components based on C, seems to mean moving this second iterator on A programmatically.
    How is this generally achieved using the ADF ? I've seen content about chaining master-detail-detail, but this is really master-detail(xN). View links only ever specify 2 tables. It seems I need to put some code in somewhere to move associated iterators when another iterator is moved.
    Also, is there an equivalent java code-point for the when-new-record-instance - ie: when an iterator moves to a different record, whether that be new or not. Not being able to find it thus far, I've put code in the executeQuery of the detail VO which fires when I need it, but there must be a better place.
    Thanks for the help.
    Edited by: litch on Jul 29, 2009 11:20 AM

    You can manipulate your AM Data Model so both details will be under the same master (as long as there are viewLinks from the master to both).
    Then you can drag them to the page and add PPR as described here:
    http://blogs.oracle.com/shay/2008/05/master_with_two_details_on_the.html

  • Can  object(instance TreeMap) be inserted in a File by objectoutputstream??

    Can a object containing TreeMap instance be inserted in a File by objectoutputstream??
    class pfore{
    static class TextFile
              String category;
              String filename;
                    TreeMap filewords;
                    TextFile( )
                    {category=filename=null;
                     filewords=new TreeMap();
                    TextFile(String category,String filename,TreeMap filewords)
              this.category=category;
              this.filename=filename;
                   // this.filewords=new TreeMap();
                    this.filewords=new TreeMap(filewords);
    public static void main (String args[]){
    //creating an object of TextFile by reading a text file and also initializing it
    TextFile ob=new TextFile("dd","ff",kp);
    //kp is a created TreeMap object
    *__try{    FileOutputStream fos= new FileOutputStream("serrial.txt");__*
               *__ObjectOutputStream oos=new ObjectOutputStream(fos);__*
                *__oos.writeObject(ob);__*               
                 *__oos.flush();__*
                 *__oos.close();__*
                      *__catch(IOException e) {__*
           *__System.out.println("exception while opening the filestream"+e);__*
           *__e.printStackTrace();__*
           *__System.exit(0);__*
    }//end main
    }//end class
    Please see the underlined part because other parts are completely ok.
    it's giving exceptions like
    at.java.io.objecstreamclass invokewriteObject
    at.java.io.objectoutputstream.writeserialData
    at.java.io.objectoutputstream.writeOrdinaryObject.etc..etc

    suppose a class is a textfile in java..containing a TreeMap instance ,and two string variables as instance..
    class textfile implements Serializable
    String foo;
    String foo1;
    TreeMap t;
    textfile t=new textfile( );now how to write object t in file??
    with objectoutputstream i have tried it..bt it is throwing exceptions..
    the details i have posted in my previous Question(see above-the code)
    please give in details how to do this??

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

  • Trying to understand iterators

    Hello again world.
    I written this little program to try and get an understanding of iterators. I chose to use a Vector object arbitrarily.import  java.util.*;
    public  class  ForumEx  extends  Vector
          public  ForumEx()
                Double  number = new  Double(12.34);
                Calendar  today = new  GregorianCalendar();
                Date  date = today.getTime();
                add("Why a duck, why a no chicken?");
                add(number);
                add(date);
                Iterator  list = iterator();
                while (list.hasNext())
                   System.out.println(list.next());
          public  static  void  main(String[]  params)
             new  ForumEx();
    }1. From where is the iterator() method being inherited? The Vector API indicates the inheritance is coming from both the abstract class AbstractList and the List interface, which in turn, seem to inherit from a choice of either the AbstractCollection class, the Collection interface, or again, the List interface. I'm confused by the whole thing.
    2. Since all the aggregate data structures I've examined so far have a mechanism to access their elements - a subscript notation or some type of index and either a size or length member, of what use are iterators in the first place?
    Can anyone make this all clear?
    Thank you one and all.
    Ciao for now.

    1. From where is the iterator() method being
    inherited?Iterator is an interface which specifies 3 methods (you find it described in the Java API documentation). Collections basically pass an object of a private class implementing the Iterator interface when asked for an iterator. The structure looks something like this,
    public class SomeCollection {
       private class Iter implements Iterator {
          // implements the Iterator interface adapted to this SomeCollection object
       public Iterator getIterator() {
          return new Iter(); // object of inner class implementing Iterator is returned
    2. Since all the aggregate data structures I've
    examined so far have a mechanism to access their
    elements - a subscript notation or some type of index
    and either a size or length member, of
    what use are iterators in the first place?Iterator basically is a design pattern describe in the "Gang of four" book. As has been said it's a general way to iterate through collections.

  • Problem with TreeMap and Vector

    Hello,
    this is the problem I have:
    I declare a Vector like this:
    Vector<String> theVector = new Vector<String>();
    I put the String needed into the Vector:
    theVector.add("blabla")
    In the other hand I had created a TreeMap like this:
    private TreeMap<Integer, Vector<String>> theTreeMap;
    I now when I try to put the Key and the Element like this my program crash:
    theTreeMap.put(1096,theVector);
    I think I don't put the data on the good way in the TreeMap...
    Any Idea? Thank you very much

    In the other hand I had created a TreeMap like this:
    private TreeMap<Integer, Vector<String>> theTreeMap;
    I now when I try to put the Key and the Element like
    this my program crash:
    theTreeMap.put(1096,theVector);What do you mean?

  • Problem with TreeMap

    I had a problem that I believe was similar to this posting:
    http://forum.java.sun.com/thread.jsp?forum=24&thread=200558
    although mine involves a TreeMap. I am adding approximately 250 mappings to a TreeMap, where the key is a String. Each key is unique, and, just to be sure, I analyzed the hashCode of each key, and they were also unique.
    After adding all of the mappings, however, the total size of the TreeMap is only 40! Somewhere, app. 210 mappings were overwritten. I added some debug code and found that after I added the 10th element, the size of the TreeMap did grow. Then the TreeMap would grow only on every 3rd mapping that I would add.
    The above-referenced posting mentioned that the rehashing of the map might cause it to overwrite existing values, so it made sense to set the initial capacity high enough to ensure that no rehashing occurred. Unfortunately, that posting dealt with a HashMap, which allows you to set the initial capacity. TreeMaps do not. In order to mimic this behavior, I added all of the mappings into a HashMap with an initial capacity of 250. When the HashMap was loaded, I created the TreeMap (with a unique Comparator), and then used the putAll() method of TreeMap to put the entire HashMap into the TreeMap. Voila! All 250 mappings were there.
    Nonetheless, this seems to be a very strange bug with TreeMap. Does anyone know why this happened?

    Sorry. Figured out the problem. It was all my fault (based on the comparator I was using, which caused the keys to be overwritten). how dare I accuse Sun of deploying buggy software. :)

Maybe you are looking for

  • Where on this site is a list of training courses?

    I wish to find out some details about the Portal/Portlet courses running in England (for 9iAS). I have tried to find them on this site, but I have failed. Could someone please point me in the right direction Thanks

  • My computer just started asking what program to use to run firefox. what happened and how do I fix? Thanks

    I just installed Firefox a few days ago and has been really good. Today my computer will not open Firefox, it keeps wanting to know what program to open in. what do I do to fix this? Thanks

  • PaaS using Oracle Database Express Edition?

    Hi, I'm planning to create a small web application that has the possibility of growing. I've been looking at some free cloud computing options for starters. I found AWS Free Tier and OpenShift. Unfortunately OpenShift does not support Oracle as an RD

  • Creating an email link/contact us pop-up

    need to create a link in which other people can contact us via our website. I do have a "contact us" page i just need to insert an email popup

  • Error in proxy login

    Hi I am using Oracle 10g and have created proxy users in DB using following code. create user app_user identified by app_user; grant create session to app_user;              create user end_user identified by end_user; grant create session, create ta