Java - Collection

I got a question regarding what type of collection class should i used based on the scenario given but i am not sure whether i am correct?
Can any1 correct me if i am wrong.
1. When a hotel is fully booked, it holds a waiting list of customers in case of
cancellations. Once a cancellation is received, the newly available room is allocated
to the first person on the waiting list, who is then deleted from the list. On a
particular day the first three customers added to the list are Ali Baba, Bibi Batek and
Charlie Chan.
class used : HashSet
2. A video shop wants to store the titles of videos available for hire. It must be possible
to list all the titles available but no particular order is required. Although the store
may have more than one copy of a particular film, the title should only appear once.
Titles available include: Iron Man, Crystal Skull and Dr Doplenty.
class used : Collection - ArrayList
3. An ICT203 tutor wants to store her students' myUniSIM names as strings in such a
way that she can easily look up an individual student, as in the table below. There are
no two students in her group with the same name.
Student’s name myUniSIM name
Charlie Dickens Charles Dickens
Margie Hector Margaret Hector
Terry Martin Terence Martin
class used : HashMap

Hi,
this sounds to me as if you just received some homework and you made a more or less blind guess?
I suggest you first take a good look at the JavaDoc for each of the Collection classes you mentioned, because just as a starter: the HashSet you suggest for your first question provides no way of returning elements in any particular order. This is obvious from the JavaDoc showing no getFirst() or whatsoever, only an iterator()-Method, but this method is documented as follows:
public Iterator<E> iterator()
Returns an iterator over the elements in this set. The elements are returned in no particular order.
So please, read the docs available and make up your mind again.
Bye.

Similar Messages

  • One to many relationship using java collections

    I am facing issue on how to store and then retrieve data . In my program which is simple java class i am retrieving data at 3 places from an xml. i need to store this temporarly in particular fashion as data is related and needed to be used later on at end program to generate report.
    first data i am retireving is employee names eg Tom , Reggie, Martha.
    Second data is department (Each employee belongs to 1 or many department ) so in this case
    Tom : Billing
    Reggie : Admin , HR
    Martha : IT
    Third data is Department number (This has 1 : 1 relationship with Department )
    Billing :01
    Admin :02
    HR:03
    IT:04
    So when i am parsing xml first i am getting employee data, then department and lastly department number. I need to store it in collection in such way later on i can retireve and link data and use it.....
    Which java collections i should use....
    Any hints or guidance ....

    Well, the simplest approach is to initially load the employees objects into a List<Employee>. Initially they store the department number only. Then load the departments, probably into a Map<Integer, Department>. Having popluated such a map you then loop through the Employee list, connecting looking up the deparment number in the map and connecting Employee to Department as you wish. (An Employee would probably had a reference to the Department, the Department might contain a List<Employee>).
    The implementations to use depend on how you'll use them. HashMaps are faster than TreeMaps, but a TreeMap orders. LinkedLists are faster to process in sequence than ArrayList, slower to process at random.

  • Possible to keep contents of Java Collection after closing program??

    Hiya
    Is there any classes in the java library that allows you to save contents of a collection such as HashMap/ArrayList etc into a so called offline collection so that next time when start up of program the contents wont disappear? Because i know when you close a program, the contents of the collections is obviously discarded and resetted for next start up of the program.
    Or is there a way to do that?
    In general i want to keep contents that are in a java collection during its use in a program session so that next time starting the program up again the collection content is still there.
    Thanks.

    Also, remember when u serialize a class every element of it should be serializable .What happens if the class elements not all are serializable? Does that mean i cant serialise that class?
    *all i want is to serialise a class which has a HashMap. The hashmap is the object which i want to serialise.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • EntityCursor to a Java Collection (ArrayList)

    Hello,
    Is there an utility Class or a method that can to put an EntityCursor Object to a java Collection (lets say an ArrayList) Object ?
    let me say a method that do this transformation :
    where EntityCursor users
    and ArrayList usersList
    try {
    for (User user : users) {
    usersList.add(user);
    } finally {
    users.close();
    Thanks
    Fahmi

    Do you mean if there are any utilities in JE which do the same transformation as you did in the method you provided?
    No, JE does not have such utilities, and you have to transform it manually, just like what you did in that method.
    But if you want to read/write the database as standard Java collections API (e.g., SortedMap), you may use JE's collections API. Please refer to the JE javadocs of the package com.sleepycat.collections.
    Thanks.
    Eric Wang
    BDB JE Team

  • Using the java collections

    I have some questions about implementing a java core collections class(in this
    case TreeSet)...
    import java.util.*;
    class SortA extends TreeSet
    public SortA()
    super();
    public SortA(int y)
    super(y);
    When I compile this(it is not the complete program btw) i get a warning:
    serializable class SortA has no definition of serialVersionUID
    So my questions are these: Why am I getting this warning? is there a way to get around this? is it possible to extend the core classes?

    So my questions are these: Why am I getting this
    warning?Because TreeSet is Serializable and Serializable insists on having a long-type filed named serialVersionUID.
    is there a way to get around this?add
    public final long serialVersionUID = 1;
    or something.
    is it
    possible to extend the core classes?Sure.

  • What java collection for large amount of data and user customizable record

    I'm trying to write an application which operates on large amount of data. I want user could customize data structure (record) from different types of variables(float,int,bool,string,enums). These records should be stored in some kind of Array. Size of record: 1-200 variables; size of Array of those records: about 100000 items (one record every second through whole day). I want these data stored in some embedded database (sqlite, hsqldb) - access using simple JDBC. Could you give me some advise how to design thoses data strucures. Sincerely yours :)
    Ok, maybe I give some example. This will be some C++ code.
    I made an interface:
    class ParamI {
    virtual string toString() = 0;
    virtual void addValue( ParamI * ) = 0;
    virtual void setValue( ParamI * ) = 0;
    virtual BYTE getType() = 0;
    Than I made some template class derived from interface ParamI:
    template <class T>
    class CParam : CParamI {
    public:
         void setValue( T val );
         T getValue();
         string toString();
         void setValue( ParamI *src ) {
              if ( itemType == src->getType() ) {
                   CParam<T> ptr = (CParam<T>)src;
                   value = ptr->value;
    private:
         BYTE itemType;
         T value;
    sample constructor of <int> template:
    template<> CParam<int>::CParam() {
         itemType = ParamType::INTEGER;
    This solution makes me possible to write collection of CParamI:
    std::vector<CParamI*> myCollection;
    CParam<int> *pi = new CParam<int>();
    pi->setValue(10);
    myCollection.push_back((CParamI*)pi);
    Is this correct solution?. My main problem is to get data from the collection. I have to check its data type using getType() method of CParamI interface.
    Please could give me some advise, some idea to make it right using java.

    If you have the requirement that you have to be able to configure on the fly, then what I've done in the past is just put everything into data pairs into a list: something along the line of: (<Vector>, <String>), where the Vector would store your data and String would contain a data type. I would then make a checker to validate the input according to the SQL databypes that I want to support on the project. It's not a big deal with the amount of data you are talking about.
    The problem you're going to have is when you try to allow dynamic definition, on the fly, of data being input to a table that has already been defined. Your DB will not support that, unless you just store that data pair--which I do not suggest.

  • Java Collection to XML

    Hi,
    I am in the midst of a project where I need to take exisitng Java objects, e.g. Collection or other data structures and create XML output.
    (1) Is TopLink the tool for me.
    (2) I am using Oracle AS 10g 10.1.2.2.0. What version of TopLink is appropriate if it is the right tool?
    thx,
    Gary

    Hi,
    You can covert the XML to Java and vice versa in TopLink using JAXB.
    if you are using JDeveloper as development platform.You can use JAXB1.0 and 2.0 Wizards that supports converting xml schema to Java and viceversa.
    TopLink is bundled with JAXB for marshalling and unmarshalling Java to XML and tooling support for the same is available in JDeveloper.
    Please refer to the link on TopLink - http://www.oracle.com/technology/products/ias/toplink/technical/tl10g_fov.html.
    which gives you more details on Object-XML using JAXB that is bundled in TopLink 10g (10.1.3.1.0).
    Hope this helps.
    Regards,
    Vinay

  • Java collection use within c++ program through CORBA

    How I use java.util.collection (i.e. Vector, ArrayList) within c++ program through CORBA (Orbacus 4.xx) with Linux, please help me...

    Use CORBA. It's the best way. I had the same dilema and CORBA was my choice. I implemented a server object in C++ that calls existing functions from dlls developed by an other team for a Window based application. The client is represented by a set of servlets that invoke methods on the C++ CORBA implemented server. I preferred to use the Apache + Tomcat combination.
    I found JNI difficult to use an not flexible enough.
    I did not even planed to try to use Runtime.getRuntime.exec. The overhead and resource usage make this solution impossible for a multiuser web application.
    CORBA works fast, is well supported. I found easy to implement both the java client servlets and the C++ servler and I didn't have much knowledge in CORBA.
    So my oppinion is to start learning CORBA

  • Java Collection addAll method parameters too restrictive

    Can anyone tell me why Java Sun does not allowed to add elements to Collection using addAll(List<?>) instead of addAll(List<? extends E>)?

    TNT wrote:
    It meant to prove that Yes, we can and we should allow addAll(List<?> c) instead of addAll(List<? extends E>) because the reasons I tries to explain here.No, we should not. It is correct as it is, for the reasons I stated. List<?> and List<Object> are effectively the same as far as this issue goes, and both +break compile-time type-safety* as I already demonstrated.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Help Required In Java Collections.

    Hi Techi's
    Can U please Solve my problem.
    The Problem ..
    I have a array
    tempentries[entryinc]=entryValue.length();this array after getting all the length for the entryValue length,
    i am trying to save the information of tempentries into some Collections like Vector...
    in the format.
    first element of tempentries in first Vector,
    second element of tempentries in second Vector,
    but i could not create a array of Vectors .
    if u r getting a idea about this please tell me.

    thnx for ur reply..
    i am sorry for not explaining my problem properly.
    i have certain Strings(There Can Be Any No. Of Strings)..
      <table>
        <row>
          <entry>dsad</entry>
          <entry>dasdasd</entry>
          <entry>bfdgsfg</entry>
          <entry>gsdfgaerg</entry>      
        </row>
        <row>
          <entry>argeragav</entry>
          <entry>agaergvdf</entry>
          <entry>adgagaads</entry>
          <entry>vaferv ev</entry>      
        </row>
      </table>
      This is the file. for each row there is 4 <entry> so i will be creating int array of size 4.
    Here There Are 2 rows but four columns.
    I need To Find a column width.So I Decided To store the first row's First entry in one vect and second entry in second ..and similarly i add for to the same respective vector for the next row..
    did u get it ..
    is there any other way to capture or read by columns of the table.

  • Java Collections Framework Architectural Flaw

    Here is this flaw (or miss) on design level:
    public interface Set<E>
    extends Collection<E>My opinion is that Set<E> should extend List<E> because a List, can BE also (or have the semantics of) a Set.
    (After all a list CAN have distinct elements)
    I.e.
    List extends Collection
    Set extends List
    Is there some argument for this proposal ?
    Edited by: javaUserMuser on Aug 13, 2008 4:04 PM

    A Set can be a list, because, although the former has not an "order", its elements could be logically accessed by means of 1st, 2nd, 3rd etc.But a List is ordered by definition.
    After all it has an iterator, which i dont like in general, because of its sequential access semanticsBut a List is ordered by definition.
    and would prefer a List implementation (and its get(int) method),which provides random access...But a List is ordered by definition.
    I.e. A Set extends the semantics of a List (which has 1st, 2nd, semantics, although not orderedBut a List is ordered by definition.
    the order i talk about is arbitrary)But a List is ordered by definition.
    ...and of course the Set has this property too... why not ?But a List is ordered by definition.
    A Set could be possibly passed to a method when a List was required, and function properlyBut a List is ordered by definition.
    there is this substitution principle satisfied .. provided that:
    List Javadoc:
    An ordered collection (also known as a sequence)...this is not present there.But a List is ordered by definition.
    i.e. a subset of all List implementations should be ordered. I.e. A list should offer 1st, 2nd semantics and not (necessarily) Comparable one, But a List is an ordered sequence, by definition.
    I.E. A set should BE an unordered List. this is what I mean
    lets brainstormLet's not.

  • Best possible way to achieve HashMap (Java Collection) in ABAP

    Hi
    I need to store name-value pair at runtime, where name act as a key (something what HashMap provides in Java). What is the best possible approach to do this?
    I can create a Structure (having two fields name and value) and then a Table Type on this structure to store multiple values, but how to make it unique?
    Please help.
    Regards,
    Arpit.

    Hi,
    In ABAP you can define table with KEY as unique.
    You also have different types of table in SAP. (Standard, Hashed, Sorted).
    You can refer to the link for details.
    http://help.sap.com/erp2005_ehp_03/helpdata/EN/fc/eb36c8358411d1829f0000e829fbfe/frameset.htm
    Regards,
    Saurabh

  • Collection in Java Question

    Hello everyone! I am rather new to the concept of Collections in Java (I have used extensively collections in VB).
    I am trying to find how collections in java work, so I used a CASE tool that automatically generates code. I am trying to model the simplest case of a maritime company that owns some ships.
    However the code that is generated by this tool can not be compiled in JBuilder. I have two classes one called "Company" and another called "Ship". The code is the following one (the errors that I receive are in the code):
    //Company.java
    public class Company
        public final Set getShips()
            if (ships == null)
                return java.util.Collections.EMPTY_SET;
            return java.util.Collections.unmodifiableSet(ships);
    // I GET AN ERROR IN THE FOLLOWING LINE SAYING: "Company.java: cannot resolve symbol: class Ship in class shipcompany.Company at line 31, column 32"
        public final void addShips(Ship arg)
            if (arg != null)
                if (ships == null)
                    ships = new LinkedHashSet();
                if (ships.add(arg))
                    arg.setCompany(this);
    // I GET AN ERROR FOLLOWING LINE : "Company.java: cannot resolve symbol: class Ship in class shipcompany.Company at line 48, column 35"
        public final void removeShips(Ship arg)
            if (ships != null && arg != null)
                if (ships.remove(arg))
                    arg.setCompany(null);
        public Company()
        public Set ships;
        protected String CName;
    //Ship.java
    public class Ship
        public final Company getCompany()
            return company;
        public final void setCompany(Company arg)
            if (company != arg)
                Company temp = company;
                company = null;//to avoid infinite recursions
                if (temp != null)
                    temp.removeShips(this);
                if (arg != null)
                    company = arg;
                    arg.addShips(this);
        public Ship()
        public Company company;
        protected String SName;
        protected int NumOfCrew;
        protected String TypeOfShip;
    } I have read the Java tutorial on collections, but I was wondering if there are any good code samples on Java Collections.
    I am after a code sample that implements a relationship 1 to many like one Company has many ships.
    Thank you very much for your responses. I am sorry for the long post!

    First of all, those errors are telling you there's a CLASSPATH problem. You need to compile and run like this:
    javac -classpath . *.java
    java -classpath . YourMainClassNote the "dot" after "-classpath". That tells the class loader to start looking in the current directory for the .class files it needs.
    Read the Sun coding standards for Java:
    http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html
    You're using a VB coding standard. Variables should start with a lower case letter (e.g., change NumOfCrew to numOfCrew).
    Make that Set of ships private, not public.
    You'll have to import java.util.Set and java.util.LinkedHashSet, of course.
    Bad idea having two empty constructors. A constructor should leave a class ready to go, fully initialized. I'd rewrite the Company ctor like this:
        public Company()
            this("", new LinkedHashSet());
        public Company(final String companyName, Collection ships)
            this.companyName = companyName;
            this.ships = new LinkedHashSet(ships);
        }Now your collection of ships isn't null, all ready to go. - MOD

  • Redesigning the Collections Framework

    Hi!
    I'm sort of an experienced Java programmer, in the sense that I program regularly in Java. However, I am not experienced enough to understand the small design specifics of the Collections Framework (or other parts of Javas standard library).
    There's been a number of minor things that bugged me about the framework, and all these minor things added up to a big annoyance, after which I've decided to (try to) design and implement my own framework.
    The thing is however, that since I don't understand many design specifics about the Collection Framework and the individual collection implementations, I risk coming up short with my own.
    (And if you are still reading this, then I thank you for your time, because already now I know that this entry is going to be long. : ) )
    Since I'm doing my Collection framework nearly from scratch, I don't have to worry too much about the issue of backwards compatibility (altough I should consider making some parts similar to the collection framework as it is today, and provide a wrapper that implements the original collection interfaces).
    I also have certain options of optimizing several of the collections, but then again, there may be very specific design issues concerning performance and usability that the developers of the framework (or other more experienced Java progammers) knew about, that I don't know.
    So I'm going to share all of my thoughts here. I hope this will start an interesting discussion : )
    (I'm also not going to make a fuss about the source code of my progress. I will happily share it with anyone who is interested. It is probably even neccessary in order for others to understand how I've intended to solve my annoyances (or understand what these annoyances were in the first place). ).
    (I've read the "Java Collections API Design FAQ", btw).
    Below, I'm going to go through all of the things that I've thought about, and what I've decided to do.
    1.
    The Collections class is a class that consists only of static utility methods.
    Several of them return wrapper classes. However the majority of them work on collections implementing the List interface.
    So why weren't they built into the List interface (same goes for methods working only with the Collection interface only, etc)? Several of them can even be implemented more efficiently. For example calling rotate for a LinkedList.
    If the LinkedList is circular, using a sentry node connecting the head and tail, rotate is done simply by relocating the sentry node (rotating with one element would require one single operation). The Collections class makes several calls to the reverse method instead (because it lacks access to the internal workings of a LinkedList).
    If it were done this way, the Collections class would be much smaller, and contain mostly methods that return wrapped classes.
    After thinking about it a while, I think I can answer this question myself. The List interface would become rather bloated, and would force an implementation of methods that the user may not need.
    At any rate, I intend to try to do some sort of clean-up. Exactly how, is something I'm still thinking about. Maybe two versions of List interfaces (one "light", and the other advanced), or maybe making the internal fields package private and generally more accessible to other package members, so that methods in other classes can do some optimizations with the additional information.
    2.
    At one point, I realized that the PriorityQueue didn't support increase\decrease key operations. Of course, elements would need to know where in the backing data structure it was located, and this is implementation specific. However, I was rather dissapointed that this wasn't supported somehow, so i figured out a way to support this anyway, and implemented it.
    Basically, I've wrapped the elements in a class that contains this info, and if the element would want to increase its key, it would call a method on the wrapping class it was contained in. It worked fine.
    It may cause some overhead, but at least I don't have to re-implement such a datastructure and fiddle around so much with the element-classes just because I want to try something with a PriorityQueue.
    I can do the same thing to implement a reusable BinomialHeap, FibonacciHeap, and other datastructures, that usually require that the elements contain some implementation-specific fields and methods.
    And this would all become part of the framework.
    3.
    This one is difficult ot explain.
    It basically revolves around the first question in the "Java Collections API Design FAQ".
    It has always bothered me that the Collection interface contained methods, that "maybe" would be implemented.
    To me it didn't make sense. The Collection should only contain methods that are general for all Collections, such as the contains method. All methods that request, and manipulate the Collection, belonged in other interfaces.
    However, I also realized that the whole smart thing about the current Collection interface, is that you can transfer elements from one Collection to another, without needing to know what type of Collection you were transferring from\to.
    But I still felt it violated "something" out there, even if it was in the name of convenience. If this convenience was to be provided, it should be done by making a separate wrapper interface with the purpose of grouping the various Collection types together.
    If you don't know what I'm trying to say then you might have to see the interfaces I've made.
    And while I as at it, I also fiddled with the various method names.
    For example, add( int index, E element), I felt it should be insert( int index, E element). This type of minor things caused a lot of confusion for me back then, so I cared enough about this to change it to somthing I thought more appropriate. But I have no idea how appropriate my approach may seem to others. : )
    4.
    I see an iterator as something that iterates through a collection, and nothing else.
    Therefor, it bothered me that the Iterator interface had an optional remove method.
    I myself have never needed it, so maybe I just don't know how to appreciate it. How much is it used? If its heavily used, I guess I'm going to have to include it somehow.
    5.
    A LinkedList doesnt' support random access. But true random access is when you access randomly relative to the first index.
    Iterating from the first to the last with a for statement isn't really random access, but it still causes bad performance in the current LinkedList implementation. One would have to use the ListIterator to achieve this.
    But even here, if you want a ListIterator that starts in the middle of the list, you still need to traverse the list to reach that point.
    So I've come up with LinkedList that remembers the last accessed element using the basic methods get, set, remove etc, and can use it to access elements relatively from it.
    Basically, there is now an special interal "ListIterator" that is used to access elements when the basic methods are used. This gives way for several improvements (although that may depend how you look at it).
    It introduces some overhead in the form of if-else statemenets, but otherwise, I'm hoping that it will generally outperform the current LinkedList class (when using lists with a large nr of elements).
    6.
    I've also played around with the ArrayList class.
    I've implemented it in a way, that is something like a random-access Deque. This has made it possible to improvement certain methods, like inserting an element\Collection at some index.
    Instead of always shifting subsequent element to the right, elements can be shifted left as well. That means that inserting at index 0 only requires a single operation, instead of k * the length of the list.
    Again, this intrduces some overhead with if-else statements, but is still better in many cases (again, the List must be large for this to pay off).
    7.
    I'm also trying to do a hybrid between an ArrayList and a Linked list, hopefully allowing mostly constant insertion, but constant true random access as well. It requires more than twice the memory, since it is backed by both an ArrayList and a LinkedList.
    The overhead introduced , and the fact that worst case random access is no better than that of a pure LinkedList (which occurs when elelements are inserted at the same index many times, and you then try to access these elements), may make this class infeasible.
    It was mostly the first three points that pushed my over the edge, and made me throw myself at this project.
    You're free to comment as much as you like.
    If no real discussion starts, thats ok.
    Its not like I'm not having fun with this thing on my own : )
    I've started from scratch several times because of design problems discovered too late, so if you request to see some of the source code, it is still in the works and I would have to scurry off and add a lot of java-comments as well, to explain code.
    Great. Thanks!

    This sort of reply has great value : )
    Some of them show me that I need to take some other things into consideration. Some of them however, aren't resolved yet, some because I'm probably misunderstanding some of your arguments.
    Here goes:
    1.
    a)
    Are you saying that they're were made static, and therefor were implemented in a utility class? Isn't it the other way around? Suppose that I did put them into the List interface, that would mean they don't need to be static anymore, right?
    b)
    A bloated List interface is a problem. Many of them will however have a default not-so-alwyas-efficient implementation in a abstract base class.
    Many of the list-algorithms dump sequential lists in an array, execute the algorithm, and dump the finished list back into a sequential list.
    I believe that there are several of them where one of the "dumps" can be avoided.
    And even if other algorithms would effectively just be moved around, it wouldn't neccesarily be in the name of performance (some of them cannot really be done better), but in the name of consistency\convenience.
    Regarding convenience, I'm getting the message that some may think it more convenient to have these "extra" methods grouped in a utility class. That can be arranged.
    But when it comes to consistency with method names (which conacerns usability as well), I felt it is something else entirely.
    For example take the two methods fill and replaceAll in the Collections class. They both set specific elements (or all of them) to some value. So they're both related to the set method, but use method names that are very distinguished. For me it make sense to have a method called setAll(...), and overload it. And since the List interface has a set method, I would very much like to group all these related methods together.
    Can you follow my idea?
    And well, the Collections class would become smaller. If you ask me, it's rather bloated right now, and supports a huge mixed bag of related and unrelated utitlity methods. If we should take this to the extreme, then The Collections class and the Arrays class should be merged.
    No, right? That would be hell : )
    2,
    At a first glance, your route might do the trick. But there's several things here that aren't right
    a)
    In order to delete an object, you need to know where it is. The only remove method supported by PriorityQueue actually does a linear search. Increase and decrease operations are supposed to be log(n). Doing a linear search would ruin that.
    You need a method something like removeAt( int i), where i would be the index in the backing array (assuming you're using an array). The elemeny itself would need to know that int, meaning that it needs an internal int field, even though this field only is required due to the internal workings of PriorityQueue. Every time you want to insert some element, you need to add a field, that really has nothing to with that element from an object-oriented view.
    b)
    Even if you had such a remove method, using it to increase\decrease key would use up to twice the operations neccesary.
    Increasing a key, for example, only requires you to float the element up the heap. You don't need to remove it first, which would require an additional log(n) operations.
    3.
    I've read the link before, and I agree with them. But I feel that there are other ways to avoid an insane nr of interfaces. I also think I know why I arrive at other design choices.
    The Collection interface as it is now, is smart because it can covers a wide range of collection types with add and remove methods. This is useful because you can exchange elements between collections without knowing the type of the collection.
    The drawback is of course that not all collection are, e.g modifiable.
    What I think the problem is, is that the Collection interface is trying to be two things at once.
    On one side, it wants to be the base interface. But on the other side, it wants to cast a wide net over all the collection types.
    So what I've done is make a Collection interface that is infact a true base interface, only supporting methods that all collection types have in common.
    Then I have a separate interface that tries to support methods for exchanging elements between collections of unknown type.
    There isn't neccesarily any performance benefit (actually, it may even introduces some overhead), but in certainly is easier to grasp, for me at least, since it is more logically grouped.
    I know, that I'm basically challenging the design choices of Java programmers that have much more experience than me. Hell, they probably already even have considered and rejected what I'm considering now. In that case, I defend myself by mentioning that it isn't described as a possiblity in the FAQ : )
    4.
    This point is actually related to point 3., becausue if I want the Collection interface to only support common methods, then I can't have an Iterator with a remove method.
    But okay....I need to support it somehow. No way around it .
    5. 6. & 7.
    The message I'm getting here, is that if I implement these changes to LinkedList and ArrayList, then they aren't really LinkedList and ArrayList anymore.
    And finally, why do that, when I'm going to do a class that (hopefully) can simulate both anyway?
    I hadn't thought of the names as being the problem.
    My line of thought was, that okay, you have this arraylist that performs lousy insertion and removal, and so you avoid it.
    But occasionally, you need it (don't ask me how often this type of situation arises. Rarely?), and so you would appreciate it if performed "ok". It would still be linear, but would often perform much better (in extreme cases it would be in constant time).
    But these improvements would almost certainly change the way one would use LinkedList and ArrayList, and I guess that requires different names for them.
    Great input. That I wouldn't have thought of. Thanks.
    There is however some comments I should comment:
    "And what happens if something is suibsequently inserted or removed between that element and the one you want?"
    Then it would perform just like one would expect from a LinkedList. However if that index were closer to the last indexed position, it would be faster. As it is now, LinkedList only chooses either the first index or the last to start the traversal from.
    If you're working with a small number of elements, then this is definitely not worth it.
    "It sounds to me like this (the hybrid list) is what you really want and indeed all you really need."
    You may be right. I felt that since the hybrid list would use twice as much memory, it would not always be the best choice.
    I going to think about that one. Thanks.

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

Maybe you are looking for

  • When I tried to Mail Merge for Data is is not exporting any data.

    HI, EBS-12.1.3 DB-11gR1 OS - RHEL 5.6 [With my Login User and SysAdmin Login User] When I enter into to the "People -> Enter and Maintain" Form and then I press the "Export Button", there is error Alert Function is not available to this responsibilit

  • I've got a green light but express not connecting to speakers

    I've configured my express to my home's wireless network and its attached to my stereo and speaker inputs via rca cables, but when I try connecting to them via iTunes Airplay drop down menu, i can't get no satisfaction, or connection. There is a soli

  • Restored Computer, can I save my applications?

    I recently had to totally reinstall Snow Leopard, and was able to restore most of my files, but unfortunately my backup did not include several recently purchased applications that are present on my iPhone (I don't sync too often). Now that I've rest

  • Hash Cluster Tables vs Partitioning

    Hi All, Can we create partition on Cluster tables? As per understanding Cluster can give excellent performance if used carefully, in our case we need to purge our data also. We can purge the partitions easly. Can you help me for the comparion of thes

  • Can an Inhouse built C# application be hosted on DB Cloud Service

    Hi Experts, I have a query from one of our customers. They are running their own inhouse built C# application using .NET Framework 3.5 and would like to run this application on Oracle Database Cloud service. Can someone please advice if this is possi