Inserting In a List

Discussion in 'Java' started by subhabangalore@gmail.com, Apr 2, 2013.

  1. Guest

    Dear Group,

    I am taking out the files in my desktop folder, as,

    File folder = new File("C:\\Users\\subhabrata\\Desktop");

    Next, I am trying to take them out one by one as using for loop and name
    of each file is converted to String,

    for( File name :folder.listFiles()){
    String s1=name.toString();
    System.out.println("####"+s1);
    System.out.print( name );
    }

    Till this there is no issue, now I am trying to insert name of all the files in an array, generally it can be done, as,

    ArrayList<String> myList = new ArrayList<String>();
    myList.add(s1);

    But the problem I am facing is, if I put it as,

    for( File name :folder.listFiles()){
    String s1=name.toString();
    System.out.println("####"+s1);
    System.out.print( name );
    ArrayList<String> myList = new ArrayList<String>();
    myList.add(s1);
    }

    I am getting name of files individually but I want to see them as the whole bunch like,

    myList=["string1","string2","string3",...."StringN"]

    My aim is to check the names then in another for loop and if match is not found with some defined name update the list.

    I am slightly new in Java so if anyone can kindly suggest how I should address it.

    Regards,
    Subhabrata.
     
    , Apr 2, 2013
    #1
    1. Advertising

  2. Roedy Green Guest

    On Tue, 2 Apr 2013 03:11:53 -0700 (PDT),
    wrote, quoted or indirectly quoted someone who said :

    >I am getting name of files individually but I want to see them as the whole bunch like,
    >
    >myList=["string1","string2","string3",...."StringN"]


    you will need a loop that runs over the list and builds the combined
    string.
    --
    Roedy Green Canadian Mind Products http://mindprod.com
    Motors make noise, and that tells you about the feelings and attitudes
    that went into it. Something was more important than sensory pleasure --
    nobody would invent a chair or dish that smelled bad or that made horrible
    noises -- why were motors invented noisy? How could they possibly be
    considered complete or successful inventions with this glaring defect?
    Unless, of course, the aggressive, hostile, assaultive sound actually served
    to express some impulse of the owner.
    ~ Philip Slater (born: 1927 age: 85)
    The Wayward Gate: Science and the Supernatural
     
    Roedy Green, Apr 2, 2013
    #2
    1. Advertising

  3. On 04/02/2013 07:11 AM, wrote:
    > Dear Group,
    >
    > I am taking out the files in my desktop folder, as,
    >
    > File folder = new File("C:\\Users\\subhabrata\\Desktop");
    >
    > Next, I am trying to take them out one by one as using for loop and name
    > of each file is converted to String,
    >
    > for( File name :folder.listFiles()){
    > String s1=name.toString();
    > System.out.println("####"+s1);
    > System.out.print( name );
    > }
    >
    > Till this there is no issue, now I am trying to insert name of all the files in an array, generally it can be done, as,
    >
    > ArrayList<String> myList = new ArrayList<String>();
    > myList.add(s1);
    >
    > But the problem I am facing is, if I put it as,
    >
    > for( File name :folder.listFiles()){
    > String s1=name.toString();
    > System.out.println("####"+s1);
    > System.out.print( name );
    > ArrayList<String> myList = new ArrayList<String>();
    > myList.add(s1);
    > }
    >
    > I am getting name of files individually but I want to see them as the whole bunch like,
    >
    > myList=["string1","string2","string3",...."StringN"]
    >
    > My aim is to check the names then in another for loop and if match is not found with some defined name update the list.
    >
    > I am slightly new in Java so if anyone can kindly suggest how I should address it.
    >
    > Regards,
    > Subhabrata.
    >

    This comes up every so often. Guava and Apache StringUtils have
    join-type methods for concatenating list elements with a delimiter of
    your choice.

    Fact is, though, if you just want a readable debugging print of your
    List, did you not simply try

    System.out.println(myList);

    AHS
     
    Arved Sandstrom, Apr 2, 2013
    #3
  4. Stefan Ram Guest

    writes:
    >for( File name :folder.listFiles()){
    >String s1=name.toString();
    >System.out.println("####"+s1);
    >System.out.print( name );
    >ArrayList<String> myList = new ArrayList<String>();
    > myList.add(s1);
    >}


    I see two answers in this NG both not mentioning what is
    sticking out like a sore thumb from this code: The line

    ArrayList<String> myList = new ArrayList<String>();

    is within the for-loop, while it obviously should appear in
    front of it. (There might be other issues I am not aware of,
    but this one I saw immediately.)
     
    Stefan Ram, Apr 2, 2013
    #4
  5. On 04/02/2013 08:40 AM, Stefan Ram wrote:
    > writes:
    >> for( File name :folder.listFiles()){
    >> String s1=name.toString();
    >> System.out.println("####"+s1);
    >> System.out.print( name );
    >> ArrayList<String> myList = new ArrayList<String>();
    >> myList.add(s1);
    >> }

    >
    > I see two answers in this NG both not mentioning what is
    > sticking out like a sore thumb from this code: The line
    >
    > ArrayList<String> myList = new ArrayList<String>();
    >
    > is within the for-loop, while it obviously should appear in
    > front of it. (There might be other issues I am not aware of,
    > but this one I saw immediately.)
    >

    You've got a point there. :) Well, many pairs of eyes in a review is
    always better than one.

    AHS
     
    Arved Sandstrom, Apr 2, 2013
    #5
  6. Joerg Meier Guest

    On Tue, 2 Apr 2013 03:11:53 -0700 (PDT), wrote:

    > I am taking out the files in my desktop folder, as,


    > [...]


    > I am getting name of files individually but I want to see them as the whole bunch like,


    > myList=["string1","string2","string3",...."StringN"]


    You need to move the list assignment out of the loop, like so:

    final File folder = new File("G:\\Media\\TV Show");
    final ArrayList<String> myList = new ArrayList<String>();
    for (final File name : folder.listFiles()) {
    final String s1 = name.toString();
    System.out.println("####" + s1);
    System.out.print(name);
    myList.add(s1);
    }

    Otherwise, you create a new, empty list for every file name, and delete the
    previous one.

    You can then print out your list like so:

    System.out.println(myList);

    Which is really short hand for the more generic version:

    System.out.println(Arrays.toString(myList.toArray()));

    > My aim is to check the names then in another for loop and if match is not found with some defined name update the list.


    It's really not clear to me what you mean by that. You will need to restate
    it or explain it in more detail.

    Liebe Gruesse,
    Joerg

    --
    Ich lese meine Emails nicht, replies to Email bleiben also leider
    ungelesen.
     
    Joerg Meier, Apr 2, 2013
    #6
  7. On 02/04/13 11:11, wrote:
    > for( File name :folder.listFiles()){
    > String s1=name.toString();
    > System.out.println("####"+s1);
    > System.out.print( name );
    > ArrayList<String> myList = new ArrayList<String>();
    > myList.add(s1);
    > }


    (Stefan has already noted that the list must be created before the
    loop. What you have here is one list created per item in the folder,
    and each of these lists is discarded.)

    > I am getting name of files individually but I want to see them as the whole bunch like,
    >
    > myList=["string1","string2","string3",...."StringN"]


    (Arved and Roedy have mentioned some ways to get this, though I think
    you are after something different. Read on...)

    > My aim is to check the names then in another for loop and if match is not found with some defined name update the list.


    Your loop seems to have two purposes: 1) display all items in a certain
    format; 2) build an internal List object.

    Perhaps I've misinterpreted your aim, but your wish to generate a list
    of names in a string with a given format leads me to think you're under
    the impression that you need to display the names somehow in order to
    perform the check you mention. This is not necessary (nor useful,
    except for purposes of diagnosing problems). You should do the check on
    the List object, not on the formatted String.

    Firstly, if you must create a List, there's a quick way to create a
    fixed-size one from the array provided by listFiles():

    List<File> files = Arrays.asList(folder.listFiles());

    Note that this is a list of File, not String; the code below does not
    need a List<String>. If you really do need a List<String>, you could do
    something similar with folder.list() instead of folder.listFiles().

    Next, you could scan the List for a matching file. Loop over it, and
    record when you find it:

    boolean found = false;
    for (File file : files) {
    if (file.getName().equals("foo")) {
    found = true;
    break; // No need to go further.
    }
    }

    However, unless you need to keep the List around for other purposes, you
    could just use the array directly from listFiles():

    boolean found = false;
    for (File file : folder.listFiles()) {
    if (file.getName().equals("foo")) {
    found = true;
    break; // No need to go further.
    }
    }

    But it would be even simpler, if you're just looking for a particular
    leafname (like "foo"), rather than a leafname matching a given pattern
    (like anything beginning with "foo"), to create a File object
    representing that name, and checking whether the file exists:

    File candidate = new File(folder, "foo");
    boolean found = candidate.exists();

    Note that, confusingly, java.io.File represents a file name, not a file,
    so 'new File(...)' does not actually create a file.

    > and if match is not found with some defined name update the list.


    Not sure how you intend to update the List. If it's supposed to
    represent the list of files in the folder, updating the List won't
    create the missing file. Perhaps you want the rest of the program to
    suppose it exists; I don't know.

    If you really do want to update the list, you'll have to create it as
    one you can resize:

    List<File> files = new ArrayList<File>(Arrays.asList(folder.listFiles()));

    Read this inside out:

    1. listFiles(): Get the list of filenames as an array.
    2. asList(): Create a 'List view' of the array.
    3. new ArrayList(): Create a modifiable list with the same contents as
    the array.




    --
    ss at comp dot lancs dot ac dot uk
     
    Steven Simpson, Apr 2, 2013
    #7
  8. Roedy Green Guest

    On Tue, 2 Apr 2013 03:11:53 -0700 (PDT),
    wrote, quoted or indirectly quoted someone who said :

    >myList=["string1","string2","string3",...."StringN"]



    FastCat, my replacement for StringBuilder has a toCommaList that
    exports a comma-separated set of strings in one long string.

    see http://mindprod.com/products.html#FASTCAT
    --
    Roedy Green Canadian Mind Products http://mindprod.com
    Motors make noise, and that tells you about the feelings and attitudes
    that went into it. Something was more important than sensory pleasure --
    nobody would invent a chair or dish that smelled bad or that made horrible
    noises -- why were motors invented noisy? How could they possibly be
    considered complete or successful inventions with this glaring defect?
    Unless, of course, the aggressive, hostile, assaultive sound actually served
    to express some impulse of the owner.
    ~ Philip Slater (born: 1927 age: 85)
    The Wayward Gate: Science and the Supernatural
     
    Roedy Green, Apr 2, 2013
    #8
  9. Lew Guest

    wrote:
    > I am taking out the files in my desktop folder, as,


    "Taking out" I understood initially as "deleting", but I gather you mean "printing" or
    "displaying".


    > File folder = new File("C:\\Users\\subhabrata\\Desktop");


    You can also use forward slashes.

    > Next, I am trying to take them out one by one as using for loop and name
    > of each file is converted to String,


    If you indented properly your scope issues would be easier to see. The first block
    doesn't have any, but the one further down does.

    > for( File name :folder.listFiles()){
    > String s1=name.toString();
    > System.out.println("####"+s1);
    > System.out.print( name );
    > }


    I should think you'd use 'getPath()' or 'getName()' on the 'name' instance.

    > Till this there is no issue, now I am trying to insert name of all the files
    > in an array, generally it can be done, as,


    > ArrayList<String> myList = new ArrayList<String>();


    That is not an array, that is a 'List'.

    > myList.add(s1);


    > But the problem I am facing is, if I put it as,


    Again, proper indentation would reveal any scope issues.

    > for( File name :folder.listFiles()){
    > String s1=name.toString();
    > System.out.println("####"+s1);
    > System.out.print( name );
    > ArrayList<String> myList = new ArrayList<String>();
    > myList.add(s1);
    > }


    Now here you have a scope issue. You create a new 'List' in each iteration, add only
    one item to it, then throw it away. Nowhere do you create a 'List' that survives one
    loop iteration.

    > I am getting name of files individually but I want to see them as the whole bunch like,


    You show no code that demonstrates how you determine what "you" are "getting".

    Please follow
    http://sscce.org/

    > myList=["string1","string2","string3",...."StringN"]


    In that case, declare your 'List' in a scope that survives the loop.

    > My aim is to check the names then in another for loop and if match
    > is not found with some defined name update the list.


    Study "scope" and "access" in Java.

    > I am slightly new in Java so if anyone can kindly suggest how I should address it.


    What is "slightly"?

    --
    Lew
     
    Lew, Apr 2, 2013
    #9
  10. markspace Guest

    On 4/2/2013 10:46 AM, Lew wrote:

    > wrote:
    >> I am taking out the files in my desktop folder, as,


    > "Taking out" I understood initially as "deleting", but I gather you mean "printing" or
    > "displaying".


    I think he means "reading." As in he reads the file entries with these
    lines of code:

    >> File folder = new File("C:\\Users\\subhabrata\\Desktop");
    >> ... folder.listFiles()...


    >
    >> Next, I am trying to take them out one by one as using for loop and name
    >> of each file is converted to String,


    Again, "take... out" for reading from an array.

    To subhaba: "Iterate over" is often used to describe reading from an
    array in a loop (for-loop or other loop).
     
    markspace, Apr 2, 2013
    #10
  11. Usefulness of "final" (Was: Re: Inserting In a List)

    On 04/02/2013 04:08 PM, lipska the kat wrote:

    > Just as a matter of interest what's with all the finals
    >
    > particularly
    >
    > for (final File name : folder.listFiles())
    >
    > Despite initial appearances this is indeed legal as the
    > assignment is made multiple times but from the same statement.
    >
    > Given that the final keyword is, aside from a flag to the compiler for
    > possible optimization, largely documentary, what is the point of making
    > name final.


    It helps avoid accidental reassignment. And it helps distinguish
    unchanged from changed variables.

    > In fact what does peppering the code with finals do to make it easily
    > understandable to an inexperienced developer ?


    I believe in using "final" pretty often as it will immediately indicate
    which local variables are constant for a method call and which are
    modified all the time. Plus, with "final" you can easier catch errors
    in control flow:

    final String x;

    if ( someCondition() ) {
    x = y.toString();
    }
    else {
    if ( someOtherCondition() ) {
    x = "foo";
    }
    // forgot the else branch here
    x = "bar";
    }

    System.out.println("We got " + x);

    Generally I find "finally" quite useful - apparently significantly more
    useful than you do. :)

    Kind regards

    robert
     
    Robert Klemme, Apr 2, 2013
    #11
  12. Eric Sosman Guest

    On 4/2/2013 2:28 PM, markspace wrote:
    > On 4/2/2013 10:46 AM, Lew wrote:
    >
    >> wrote:
    >>> I am taking out the files in my desktop folder, as,

    >
    >> "Taking out" I understood initially as "deleting", but I gather you
    >> mean "printing" or
    >> "displaying".

    >
    > I think he means "reading." As in he reads the file entries with these
    > lines of code:
    >
    >>> File folder = new File("C:\\Users\\subhabrata\\Desktop");
    > >> ... folder.listFiles()...

    >
    >>
    >>> Next, I am trying to take them out one by one as using for loop and name
    >>> of each file is converted to String,

    >
    > Again, "take... out" for reading from an array.
    >
    > To subhaba: "Iterate over" is often used to describe reading from an
    > array in a loop (for-loop or other loop).


    Let's not give the impression that "iterate" or even "iterate
    over" implies read-only activities. If it did, why would the
    Iterator interface specify a remove() method? :)

    Typical usage is "The code iterates over the array (or list,
    or sequence, or collection), doing thus-and-such." It's the
    thus-and-such part that indicates whether reading or writing (or
    both, or something more complicated) is involved; iteration is
    just the procedure for making the visits, not their nature.

    "Iterate over the array, looking for the minimum value."

    "Iterate over the array, converting all the values from
    degrees to radians."

    If the iteration is simple or obvious (or irrelevant) it
    probably doesn't get mentioned at all: The above would likely
    be "find the minimum" and "convert degrees to radians." The
    main reason to mention the iteration itself would be if there's
    something special or unusual about it:

    "The list is sorted from smallest to largest. Iterate
    backwards to output the items in descending order."

    "Basic cocktail-shaker sort: Iterate over the list,
    exchanging adjacent pairs of elements that are out of order.
    Then make another pass, this time iterating in the opposite
    direction. Repeat, alternating directions, until a pass
    makes no exchanges."

    --
    Eric Sosman
    d
     
    Eric Sosman, Apr 2, 2013
    #12
  13. Joerg Meier Guest

    On Tue, 02 Apr 2013 15:08:53 +0100, lipska the kat wrote:

    > Just as a matter of interest what's with all the finals


    final further describes what is happening - namely, whereas "File name"
    says "I'm making a local variable named name of the type File", "final File
    name" says "I'm making a local variable named name of the type File,
    assigning it here, and then it will always stay that". In general, I prefer
    being more clear over being less clear, at the cost of being more verbose.

    > particularly


    > for (final File name : folder.listFiles())


    > Despite initial appearances this is indeed legal as the
    > assignment is made multiple times but from the same statement.


    In this case, it signals that inside the loop, name is not reassigned.
    >
    > Given that the final keyword is, aside from a flag to the compiler for
    > possible optimization, largely documentary, what is the point of making
    > name final.


    > In fact what does peppering the code with finals do to make it easily
    > understandable to an inexperienced developer ?


    It doesn't at all. I have my IDE set to automatically make final what it
    can, because I'm often lazy and forget to do it myself, and didn't even
    think about it when copying the code back (as for why I put it in my IDE in
    the first place, I wanted to confirm that Sysout(myList) was indeed
    identical to Sysout(Arrays.toString(myList.toArray())).

    So, I honestly didn't even realize that my IDE put in the finals, because
    I'm so used to it by now. Didn't give it any more thought than I gave the
    fact that my IDE did proper code formatting on it.

    In retrospect, without an explanation, it's probably more confusing than
    helpful to a newbie, so it's good that you brought the issue up.

    Liebe Gruesse,
    Joerg

    --
    Ich lese meine Emails nicht, replies to Email bleiben also leider
    ungelesen.
     
    Joerg Meier, Apr 2, 2013
    #13
  14. Eric Sosman Guest

    Re: Usefulness of "final" (Was: Re: Inserting In a List)

    On 4/2/2013 3:06 PM, Robert Klemme wrote:
    >[...]
    > I believe in using "final" pretty often as it will immediately indicate
    > which local variables are constant for a method call and which are
    > modified all the time. [...]


    De gustibus non disputandum est, but I think "final" should
    be reserved for things that *mustn't* change, and shouldn't just
    be pasted on to anything that happens to remain constant in the
    code's current incarnation. When considering a change to some
    code I might see

    Thing thing = getThing();
    // ... code that doesn't happen to change `thing'

    or I might see

    final Thing thing = getThing();
    // ... code that (obviously) doesn't change `thing'

    In the first case I might think about inserting, say,

    if (thing == null)
    thing = fallbackThing();

    .... while in the second case I wouldn't even consider it: I
    would suppose that the code relied on `thing' being exactly
    what getThing() had returned, perhaps in some way and for some
    reason not clear to me.

    But, as I said above, de gustibus.

    > Generally I find "finally" quite useful - apparently significantly more
    > useful than you do. :)


    "finally" is a Godsend -- but did you mean "final"?

    --
    Eric Sosman
    d
     
    Eric Sosman, Apr 2, 2013
    #14
  15. Eric Sosman Guest

    On 4/2/2013 5:06 PM, Martin Gregorie wrote:
    >[...]
    > Its also not clear to me whether the OP is expecting some form of sorted
    > list of filenames. If he is expecting that, it would be best to use a
    > TreeMap<String> rather than an ArrayList<String> to store the filenames.


    Is there a reason to prefer TreeMap (or other SortedMap) over
    accumulate-disordered-and-sort-afterward?

    --
    Eric Sosman
    d
     
    Eric Sosman, Apr 2, 2013
    #15
  16. Arne Vajhøj Guest

    On 4/2/2013 10:08 AM, lipska the kat wrote:
    > On 02/04/13 13:35, Joerg Meier wrote:
    >> On Tue, 2 Apr 2013 03:11:53 -0700 (PDT), wrote:
    >>
    >>> I am taking out the files in my desktop folder, as,

    >>
    >>> [...]

    >>
    >>> I am getting name of files individually but I want to see them as the
    >>> whole bunch like,

    >>
    >>> myList=["string1","string2","string3",...."StringN"]

    >>
    >> You need to move the list assignment out of the loop, like so:
    >>
    >> final File folder = new File("G:\\Media\\TV Show");
    >> final ArrayList<String> myList = new ArrayList<String>();
    >> for (final File name : folder.listFiles()) {
    >> final String s1 = name.toString();
    >> System.out.println("####" + s1);
    >> System.out.print(name);
    >> myList.add(s1);
    >> }

    >
    > Just as a matter of interest what's with all the finals
    >
    > particularly
    >
    > for (final File name : folder.listFiles())
    >
    > Despite initial appearances this is indeed legal as the
    > assignment is made multiple times but from the same statement.
    >
    > Given that the final keyword is, aside from a flag to the compiler for
    > possible optimization, largely documentary, what is the point of making
    > name final.
    >
    > In fact what does peppering the code with finals do to make it easily
    > understandable to an inexperienced developer ?


    The performance optimization benefits of final is a myth
    solid founded in how JVM's from the 1990's worked.

    The generous usage of final is an attempt to make
    Java a more functional language.

    I don't like it. If I want to program in a functional style, then
    I would pick a functional language.

    Arne
     
    Arne Vajhøj, Apr 3, 2013
    #16
  17. Joerg Meier Guest

    On Tue, 2 Apr 2013 22:52:20 +0000 (UTC), Martin Gregorie wrote:

    > On Tue, 02 Apr 2013 18:22:55 -0400, Eric Sosman wrote:
    >> On 4/2/2013 5:06 PM, Martin Gregorie wrote:
    >>>[...]
    >>> Its also not clear to me whether the OP is expecting some form of
    >>> sorted list of filenames. If he is expecting that, it would be best to
    >>> use a TreeMap<String> rather than an ArrayList<String> to store the
    >>> filenames.

    >> Is there a reason to prefer TreeMap (or other SortedMap) over
    >> accumulate-disordered-and-sort-afterward?

    > I think so, yes, because none of File's list() and listFiles() methods
    > guarantee the order of the returned files. By using TreeMap or equivalent
    > the OP gets the sort for free, should it be required.


    For free ? The cost is just distributed amongst the insert calls, and is
    likely considerably higher than with an unsorted list that has a single
    sort call once it is filled. SortedMaps are for things that need sorting
    accessible before all elements are inserted, which really isn't the case
    here.

    > I use it a lot, both for that and because accessing stored objects by key
    > from a TreeMap is almost certainly faster than scanning an ArrayMap
    > unless it contains very few objects indeed.


    Java doesn't have ArrayMaps. TreeMaps are O(log(n)) for get while a HashMap
    alternative would be O(1). I don't think Java includes any map with
    behaviour as ill coded as what you describe. Frankly, I'm having trouble
    imagining any modern language having something quite that horrible. Even
    LinkedList-Map-combinations usually are backed with some sort of HashMap.

    I don't mean to be rude, but it seems like you have lot of misconception
    about how data structures work in anything more than school/class level
    implementations.

    Liebe Gruesse,
    Joerg

    --
    Ich lese meine Emails nicht, replies to Email bleiben also leider
    ungelesen.
     
    Joerg Meier, Apr 3, 2013
    #17
  18. Arne Vajhøj Guest

    Re: Usefulness of "final" (Was: Re: Inserting In a List)

    On 4/2/2013 3:06 PM, Robert Klemme wrote:
    > On 04/02/2013 04:08 PM, lipska the kat wrote:
    >> Just as a matter of interest what's with all the finals
    >>
    >> particularly
    >>
    >> for (final File name : folder.listFiles())
    >>
    >> Despite initial appearances this is indeed legal as the
    >> assignment is made multiple times but from the same statement.
    >>
    >> Given that the final keyword is, aside from a flag to the compiler for
    >> possible optimization, largely documentary, what is the point of making
    >> name final.

    >
    > It helps avoid accidental reassignment. And it helps distinguish
    > unchanged from changed variables.


    That is a nice theory.

    I am a bit skeptic about the real world benefits.

    In the example provided it would simply never happen.

    Arne
     
    Arne Vajhøj, Apr 3, 2013
    #18
  19. Arne Vajhøj Guest

    On 4/2/2013 8:04 PM, Joerg Meier wrote:
    > On Tue, 2 Apr 2013 22:52:20 +0000 (UTC), Martin Gregorie wrote:
    >
    >> On Tue, 02 Apr 2013 18:22:55 -0400, Eric Sosman wrote:
    >>> On 4/2/2013 5:06 PM, Martin Gregorie wrote:
    >>>> [...]
    >>>> Its also not clear to me whether the OP is expecting some form of
    >>>> sorted list of filenames. If he is expecting that, it would be best to
    >>>> use a TreeMap<String> rather than an ArrayList<String> to store the
    >>>> filenames.
    >>> Is there a reason to prefer TreeMap (or other SortedMap) over
    >>> accumulate-disordered-and-sort-afterward?

    >> I think so, yes, because none of File's list() and listFiles() methods
    >> guarantee the order of the returned files. By using TreeMap or equivalent
    >> the OP gets the sort for free, should it be required.

    >
    > For free ? The cost is just distributed amongst the insert calls, and is
    > likely considerably higher than with an unsorted list that has a single
    > sort call once it is filled.


    It is not that obvious to me that:

    n O(1) + 1 O(nlogn) is that much faster than n log(n)

    > SortedMaps are for things that need sorting
    > accessible before all elements are inserted, which really isn't the case
    > here.
    >
    >> I use it a lot, both for that and because accessing stored objects by key
    >> from a TreeMap is almost certainly faster than scanning an ArrayMap
    >> unless it contains very few objects indeed.

    >
    > Java doesn't have ArrayMaps. TreeMaps are O(log(n)) for get while a HashMap
    > alternative would be O(1). I don't think Java includes any map with
    > behaviour as ill coded as what you describe. Frankly, I'm having trouble
    > imagining any modern language having something quite that horrible. Even
    > LinkedList-Map-combinations usually are backed with some sort of HashMap.
    >
    > I don't mean to be rude, but it seems like you have lot of misconception
    > about how data structures work in anything more than school/class level
    > implementations.


    I think Martin has a lot of experience.

    But I think he got this post garbled up a bit.

    As you correctly state then there are no ArrayMap. I am not even sure
    what such a beast would actually do.

    I also somewhat suspect that he really meant TreeSet not TreeMap as
    I can not see any key value pair here.

    Arne
     
    Arne Vajhøj, Apr 3, 2013
    #19
  20. Eric Sosman Guest

    On 4/2/2013 8:20 PM, Arne Vajhøj wrote:
    > On 4/2/2013 8:04 PM, Joerg Meier wrote:
    >> On Tue, 2 Apr 2013 22:52:20 +0000 (UTC), Martin Gregorie wrote:
    >>
    >>> On Tue, 02 Apr 2013 18:22:55 -0400, Eric Sosman wrote:
    >>>> On 4/2/2013 5:06 PM, Martin Gregorie wrote:
    >>>>> [...]
    >>>>> Its also not clear to me whether the OP is expecting some form of
    >>>>> sorted list of filenames. If he is expecting that, it would be best to
    >>>>> use a TreeMap<String> rather than an ArrayList<String> to store the
    >>>>> filenames.
    >>>> Is there a reason to prefer TreeMap (or other SortedMap) over
    >>>> accumulate-disordered-and-sort-afterward?
    >>> I think so, yes, because none of File's list() and listFiles() methods
    >>> guarantee the order of the returned files. By using TreeMap or
    >>> equivalent
    >>> the OP gets the sort for free, should it be required.

    >>
    >> For free ? The cost is just distributed amongst the insert calls, and is
    >> likely considerably higher than with an unsorted list that has a single
    >> sort call once it is filled.

    >
    > It is not that obvious to me that:
    >
    > n O(1) + 1 O(nlogn) is that much faster than n log(n)


    By design, O() obscures all the coefficients. If you were
    to say that n*log(n) and 9999999999999999999999999999*n*log(n)
    are both O(n*log(n)) you would be right -- but if you were to
    claim the former was not "that much faster" than the latter you
    would be wrong by a factor of 9999999999999999999999999999.

    ... and that's the gist of my question: It seems to me likely
    that the actual time to sort an ArrayList of large-ish N size will
    be less than the time to build a TreeMap (BTW, Martin probably
    meant TreeSet) of the same N items. Argument: The TreeSet expends
    effort in keeping itself always sorted all the time, while the
    ArrayList has the freedom to be disordered up until the end, and
    then to impose an ordering just once. The ArrayList is asked to
    present one sorted version of N items, while the TreeSet must
    offer sorted versions of 1,2,3,...,N items. If the intermediate
    orderings are not required, I don't see much reason to compute them.

    By the way, the ArrayList will use less memory -- but both
    will use O(n) in all, so who cares? :)

    For this insight I will charge you only O(1) pfennigs. ;-)

    --
    Eric Sosman
    d
     
    Eric Sosman, Apr 3, 2013
    #20
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Muhammad Usman
    Replies:
    1
    Views:
    1,097
    Raja Saravanan
    Oct 16, 2003
  2. Massimiliano Alberti

    Inserting an empty element in a list (STL)

    Massimiliano Alberti, Sep 24, 2003, in forum: C++
    Replies:
    3
    Views:
    413
  3. Kay
    Replies:
    1
    Views:
    389
    John Harrison
    Sep 3, 2004
  4. John Salerno

    inserting into a list

    John Salerno, Mar 7, 2006, in forum: Python
    Replies:
    15
    Views:
    650
    Steve Holden
    Mar 8, 2006
  5. =?Utf-8?B?U3Jpbmk=?=

    Inserting into DB table with date from Generic List

    =?Utf-8?B?U3Jpbmk=?=, Nov 7, 2006, in forum: ASP .Net
    Replies:
    0
    Views:
    381
    =?Utf-8?B?U3Jpbmk=?=
    Nov 7, 2006
Loading...

Share This Page