Retrieve Last element from Collection

Hi,
I am a beginner in Java. Can somebody tell me how to retrieve last element from java.util.collection without Iterating?

Hi,
I am a beginner in Java. Can somebody tell me
how to retrieve last element from
java.util.collection without Iterating?You realize of course that this is rather silly since not every Collection necessarily has a "last" element. For it to have the notion of a "last" element it would have be ordered and would be a List.

Similar Messages

  • Mail hangs upon retrieving last mail from POP account

    Hi,
    I have a problem with retrieving mail from a POP account. Mail seem to hang after the last new mail has been retrieved from the account. E.g, the activity viewer shows "Fetching 7 of 7", the progress bar indicates that all mails have been retrieved, but never completes. Pressing the Stop button next to the progress bar does not have an effect. Mail then indefinitly hangs in the "STOPPING" phase. In that state I cannot retrieve mails for other accounts, either. I have to force quit Mail.
    Has anyone experiences similar problems and found a solution?
    Thanks,
    Sascha
    iMac G5   Mac OS X (10.4.8)   Mail Version 2.1 (752/752.2)

    Does your account have webmail capability? If so, log into your account that way, and deal with the offending message.

  • Lots of blank space when printing array with only last element printed

    I have a slight problem I have been trying to figure it out for days but can't see where my problem is, its probably staring me in the face but just can't seem to see it.
    I am trying to print out my 2 dimensional array outdie my try block. Inside the trying block I have two for loops in for the arrays. Within the second for loop I have a while to put token from Stringtokeniser into my 2 arrays. When I print my arrays in this while bit it prints fine however when I print outside the try block it only print the last element and lots of blank space before the element.
    Below is the code, hope you guys can see the problem. Thank you in advance
       import java.io.*;
       import java.net.*;
       import java.lang.*;
       import java.util.*;
       import javax.swing.*;
       public class javaflights4
          public static final String MESSAGE_SEPERATOR  = "#";
          public static final String MESSAGE_SEPERATOR1  = "*";
          public static void main(String[] args) throws IOException
             String data = null;
             File file;
             BufferedReader reader = null;
             file = new File("datafile.txt");
             String flights[] [];
                   //String flightdata[];
             flights = new String[21][7];
             int x = 0;
                   //flightdata = new String[7];
             int y = 0;
             try
                reader = new BufferedReader(new FileReader(file));   
                //data = reader.readLine();   
                while((data = reader.readLine())!= null)   
                   data.trim();
                   StringTokenizer tokenised = new StringTokenizer(data, MESSAGE_SEPERATOR1);
                   for(x = 0; x<=flights.length; x++)
                      for(y = 0; y<=flights.length; y++)
                         while(tokenised.hasMoreTokens())
                            //System.out.println(tokenised.nextToken());
                            flights [x] [y] = tokenised.nextToken();
                            //System.out.print("*"+ flights [x] [y]+"&");
                   System.out.println();
                catch(ArrayIndexOutOfBoundsException e1)
                   System.out.println("error at " + e1);
                catch(Exception e)
                finally
                   try
                      reader.close();
                      catch(Exception e)
             int i = 0;
             int j = 0;
             System.out.print(flights [j]);
    //System.out.println();

    A number of problems.
    First, I bet you see a lot of "error at" messages, don't you? You create a 21x7 array, then go through the first array up to 21, going through the second one all the way to 21 as well.
    your second for loop should go to flights[x].length, not flights.length. That will eliminate the need for ArrayIndexOutOfBounds checking, which should have been an indication that you were doing something wrong.
    Second, when you get to flights[0][0] (the very first iteration of the inner loop) you are taking every element from the StringTokenizer and setting flights[0][0] to each, thereby overwriting the previous one. There will be nothing in the StringTokenizer left for any of the other (21x7)-1=146 array elements. At the end of all the loops, the very first element in the array (flights[0][0]) should contain the last token in the file.
    At the end, you only print the first element (i=0, j=0, println(flight[ i][j])) which explains why you see the last element from the file.
    I'm assuming you have a file with 21 lines, each of which has 7 items on the line. Here is some pseudo-code to help you out:
    count the lines
    reset the file
    create a 2d array with the first dimension set to the number of lines.
    int i = 0;
    while (read a line) {
      Tokenize the line;
      count the tokens;
      create an array whose size is the number of tokens;
      stuff the tokens into the array;
      set flights[i++] to this array;
    }

  • How to delete the last element of a collection without iterating it?

    how to delete the last element of a collection without iterating it?

    To add to jverd's reply, even if you could determine the last element, in some collections it is not guaranteed to always be the same.
    From HashSet:
    It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time.

  • Retrieving all UI Elements from window with Applescript

    Hi All..
    I want to retrieve all the ui elements from one of the window in runtime with Applescript.
    The problem is in order to get the elements of the particular window i need to pass thru the hierarchy like UI element 1 of scroll area 1 of window 1 etc..
    How do i get the hierarchy at the runtime??
    For eg: if the hierarchy level is 3, i can get the UI elemets like.. ui elements of ui elements of ui elements of window 1.. this works fine
    but i want to repeat the same statement in loop, till i get some elements, how do i achieve the same??
    I tried the below code its not working for me... Pls suggest
    set allButtons to {}
    set i to 0
    tell application "System Events"
        tell process "Install Adobe Reader"
            set num to count of UI elements of window 2
            set element to every UI element of window 2
                  repeat with i from 0 to num
                if class of element is button then
                    return true
                else
                    set element to (a reference to UI elements of element)
                    set num to count of UI elements of element
                    end if
            end repeat
        end tell
    end tell

    madhusudhanjr wrote:
    actually am implementing Applescripts in Java, the output what we get in Java is not exactly similar to Applescript.. Is their any way to make a list or Array of the above codes output??
    Because they are objects.
    Here's how to convert these objects in  text format :
    set allButtons to ""
    tell application "System Events"
          tell process "Install Adobe Reader"
                with timeout of 0 seconds
                      set tElements to entire contents of window 1
                end timeout
                repeat with i in tElements
                      if class of i is button then try
                            i as text
                      on error err
                            tell my cleanUpErr(err) to if it is not "" then set allButtons to allButtons & it & linefeed
                      end try
                end repeat
          end tell
    end tell
    allButtons
    on cleanUpErr(t)
          set oTID to text item delimiters
          try
                set text item delimiters to "«" -- remove description of the error at beginning of the text
                set t to "«" & (text items 2 thru -1 of t) as text
                set text item delimiters to " of «class pcap»" -- remove 'of process "xxxx" of application "System Events"'
                set r to text item 1 of t
                set text item delimiters to oTID
                return r -- return object in text format
          end try
          set text item delimiters to oTID
          return ""
    end cleanUpErr
    You will get a button to each line (the last line will be empty).
    Here is an example of the result :
    «class butT» 1 of window "xyz"
    «class butT» "bla" of window "xyz"
    «class butT» 3 of window "xyz"
    «class butT» "OK" of «class scrb» 1 of «class scra» 1 of window "xyz"
    Each line is compilable in (osascript or in the Editor) without changing the text even if some of the classes are Raw Code --> «class butT»

  • How to retrieve elements from 3 different xml file in one url

    Hi all,
    Could anyone please let me how can we retrieve elements from 3 different xml file in one url?
    i just can only do it with one file only, any help would very appreciate.
    Thank in advance
    Jim

    Hi Philip
    Thanks for replying me.
    I tried on that way, In my mdx query i am using one slice attribute (i.e [Customer].[Gender].allmembers) in rows so getting error "The  Hierarchy already appears in Axis1".
    SELECT
    {[Measures].[Internet Sales Amount] } ON 0,
    NON EMPTY
    {[Customer].[Gender].allmembers } ON 1 -- Used
    FROM
    [Adventure Works]
    WHERE
    [Customer].[Gender].&[M]
    ,[Product].[Size Range].[(All)]
    ,[Customer].[Country].[All Customers]
    [Customer].[Gender].[All Customers]
    ,[Product].[Size Range].&[XL]
    ,[Customer].[Country].[All Customers]
    [Customer].[Gender].[All Customers]
    ,[Product].[Size Range].[(All)]
    ,[Customer].[Country].&[Australia]
    Can you provide alternate ways to get resolved.
    Thanks in advance

  • Retrieving Data from Collections

    Greetings to all!!!
    I am trying to write some java code that creates an ArrayList of Time objects and then reads them back. (this as part of my assignment creating a Squash Court Booking System).
    The class Time has a method that adds minutes to the object and I use this to create 12 different timings from 9:00 to 17:15. In order to test that they are being correctly created, I add the created object (via the toString() method) to a String variable ?timeOutput?. In tests, timeOutput correctly gathers the 12 different Times.
    CODE:
    String timeOutput = "";
    //create arrayList of time objects
    Time tempTime = new Time(8,15);
    ArrayList bookingTimes = new ArrayList();
    //fill arrayList with a set of Booking Times
    for(int i =0; i < 12; ++i) {
    tempTime.addTime(45);
    bookingTimes.add(tempTime);
    timeOutput += tempTime.toString() + "\n";
    JOptionPane.showMessageDialog(null, timeOutput, "Booking Times", 1);
    My PROBLEM arises when it comes to reading back those Time objects?..I am only able to retrieve the value for the LAST item in the ArrayList (ie the Time 17:15)?..this is returned 12 times, regardless of whether the for loop or the iterator is used. This time (17:15) is also returned if I don?t use a loop/iterator at all, and just try to access one item in the Arraylist by its index value!
    CODE (using a for loop to access the index numbers of the ArrayList)
    Time tempTime_2 = new Time(9,00);
    for(int j =0; j < 12; ++j) {
    tempTime_2 = (Time)bookingTimes.get(j);
    timeOutput += tempTime_2.toString() + "\n";
    JOptionPane.showMessageDialog(null, timeOutput, "Booking Times", 1);
    CODE (using a an iterator to iterate across the ArrayList)
    Iterator timings = bookingTimes.iterator();
    while(timings.hasNext()) {
    timeOutput += ((Time)(timings.next())).toString() + "\n";
    JOptionPane.showMessageDialog(null, timeOutput, "Booking Times", 1);
    I feel that I must be repeating some basic syntax error, and feel very stuck?(and I haven?t even got on to retrieving values from nested HashMaps!!).
    I?d be very grateful for a helping hand??..I really want to know where I'm going wrong....
    cheerz 4 applying ur grey cells to my problem
    barge

    Hi all, and thanx for suggestions,
    Yatarchivist, I've tried printing booking times by retrieving the value from the ArrayList and outputting it to a JOPane........with the same result, namely that they seem to be loaded properly (see code below).
    My instinct is to agree with all of u that the problem is in loading the Array, but I can't for the life of me find the crux of the problem, or a way round it. All the tests I do seem to confirm that it's loading properly, just not regurgitating anything but the last item in the ArrayList
    for(int i =0; i < 12; ++i) {
          bookingTimes.add(tempTime);
          Time t = (Time)bookingTimes.get(i);
          JOptionPane.showMessageDialog(null, t.toString(), "Booking Times", 1);
    Pleeez, someone enlighten this troubled soul!!
          tempTime.addTime(45);     
        }

  • Delete element from a collection (JDev 10.1.2)

    Hello
    I have a bean which has a collection "testCollection" and accessors for it. This has been populated with some elements (similar to the LDAPDataControls example). I have created the data control for it and dragged the collection onto a JSP as a read only form. This displays the current element of the collection depending on the iterator position.
    I then have a forward on the page using a button to a Data Action called RemoveAction. I have overwritten invokeCustomMethod and I'm trying to remove the element in the collection at the current iteraotr position.
    I can access the iterator using actionContext.getBindingContainer().findIterator("testCollectionIterator");
    From this I can get the current row but both row.remove() and row.removeFromCollection throw UnsupportedMethod exceptions.
    I can access the collection using actionBinding.getBindingContainer().getDataControl().getDataProvider(), but I have no way of removing the object from the collection without having a reference to the object itself.
    Please can someone explain how to remove elements from the collection?
    Also can someone explain in the LDAPDataControls example why its also necessary to have a class called LDAPDataControl (type of DCGenericDataControl) and a LDAPDataControlFactory (type of DataControlFactoryImpl)?
    Just having the classes LDAPSearch, the bean class LDAPEntry, and a class to hold the collection LDAPCollection works fine. Create the data control for LDAPCollection and drag the collection onto the JSP.
    Thanks.

    I'm still not sure about this. Can anyone help? Thanks.

  • EJB ClassCastException Retrieving from Collection in same AppServer

    I am experiencing a weired Problem.
    I am passing a Collection of IdNameTO Transfer Object from My EJB Client(JSP) to EJB.
    At Server Side EJB is able to get the Object From Collection but when it does a Cast to convert the Object back to IdNameTO I get ClassCastException on IdNameTO.
    This problem happend only when Both Client and Server(EJB) are deployed on Same Application Server(WebSphere) i.e. same Virtual Machine. If Both Client and EJB are deployed on separate Servers then I don;t get any Exception.
    If I form a collection of IdNameTO in EJB and pass it to EJB Client then even on same Server I don't get any exception.

    I am experiencing a weired Problem.
    I am passing a Collection of IdNameTO Transfer Object from My EJB Client(JSP) to EJB.
    At Server Side EJB is able to get the Object From Collection but when it does a Cast to convert the Object back to IdNameTO I get ClassCastException on IdNameTO.
    This problem happend only when Both Client and Server(EJB) are deployed on Same Application Server(WebSphere) i.e. same Virtual Machine. If Both Client and EJB are deployed on separate Servers then I don;t get any Exception.
    If I form a collection of IdNameTO in EJB and pass it to EJB Client then even on same Server I don't get any exception.

  • How to retrieve the values from PL/SQL table types.

    Hi Every one,
    I have the following procedure:
    DECLARE
    TYPE t1 IS TABLE OF emp%ROWTYPE
    INDEX BY BINARY_INTEGER;
    t t1;
    BEGIN
    SELECT *
    BULK COLLECT INTO t
    FROM emp;
    END;
    This procedure works perfectly fine to store the rows of employee in a table type. I am not able to retrieve the values from Pl/SQL table and display it using dbms_output.put_line command.
    Can anybody help me please!!!!!
    Thanks
    Ahmed.

    You mean, you can't add this
    for i in t.first..t.last loop
    dbms_output.put_line(t(i).empno||' '||t(i).ename||' '||t(i).job);
    end loop;or you can't add this
    set serveroutput onor maybe, you are working in third party application where dbms_output is not applicable at all?
    You see, not able like very similar it is not working - both are too vague...
    Best regards
    Maxim

  • How to remove only the last element of spreadsheet string

    I use path to string option to store image path into database and while retrieving the string is again converted into path but it gives out an error as the output of array to spreadsheet string gives out a tab at the end which is unable for the IMAQ read file to recognise.but when i use the path of the image directly into IMAQ readfile the image is opened . so how to remove the tab only at the end of output of the spreadsheet string(whose length can vary)? I have also attached my program with this.
    Attachments:
    retrieve_images_from_DB.vi ‏65 KB
    file_path_to_db_(images).vi ‏40 KB
    create_table_for_images.vi ‏45 KB

    indhu wrote:
    > Thanks for your reply!
    > But my problem is to remove only the last element(which is a tab or an
    > alphabet) from a spreadsheet string of any length.
    If you just want to remove the last character of a string just use the
    String Size function reduce the result by one and wire it together with
    the string to the Split String function.
    Rolf Kalbermatter
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • Reading an integer size element from file

    Hello, I need some help for reading an integer size element from a file. In C++ there is the function fread with the following signature size_t fread(void ptr, size_t size, size_t nitems, FILE stream); where size is the size of one of the elements. Using this function in c++, you can read an integer by setting size = sizeof(int). I need this function because I am writing in a file a lot of integers and characters without any separator and I need to take the first element which is always an integer. Here is an example:
    I have: int x = 234; String y = "12ABC". I write those two elements in an output file. Now, when reading from that file the content of the file is: 23412ABC and I need to take the two elements x and y.
    Can anyone help ?

    I see what you mean but the problem is a bit more complicated, maybe I did not explain well. I need to copy data in a text file and retrieve them. Most data that will be written in the file are stored in an char array. those data may contain digits, letters, special characters... depending on their ASCII code. But before writting that char array, I need to write an integer corresponding to a specific index and I have no way of predicting the number of digits of that integer. So for example, my char array contains the following data: {'1','2','3','a','b','c'} and my int equals 10000. Using FileWriter I write the int and then the char array using the method myfile.write with its arguments. Next step, I want now to read from myfile.txt the data that I wrote in the first step. I start reading the int then using myfile.read(mychararray, 0, 6) /*6 being the size of the bloc to be read*/ I read the remaining characters and store each char in a cell of mychararray. The problem with this, is that using the method .read I can not read the first integer since I don't know its size: it may contain 1, 2 or even more digits.
    I know that storing everything in bytes would make my task easier, but I necessarily need to store an array of characters and then use .read method to store the content of the file (after having read the int of course) in a char array. Last clarification, the step of writing int then char array is reproduced n times before calling myfile.close();
    I hope it is clearer than before. Any suggestion for this problem would be welcome.

  • Re: [iPlanet-JATO] Re: Retrieving all Values from a Tiled View

    Todd,
    Let me try to explain you this time. I have a text field in a TiledViewBean.
    When I display the page, the text field
    html tag is created with the name="PageDetail.rDetail[0].tbFieldName" say
    five times/rows with same name.
    The html tags look like this.
    <input type=text name="PageDetail.rDetail[0].tbFieldName" value=""
    maxlength=9 size=13>
    <input type=text name="PageDetail.rDetail[0].tbFieldName" value=""
    maxlength=9 size=13>
    <input type=text name="PageDetail.rDetail[0].tbFieldName" value=""
    maxlength=9 size=13>
    When the form is submitted, I want to get the text field values using the
    method getTbFieldName().getValues() which
    returns an array object[]. This is in case where my TiledViewBean is not
    bound and it is working fine.
    Now in case when my TiledView is bound to a model, it creates the html tags
    as follows.
    <input type=text name="PageDetail.rDetail[0].tbFieldName" value=""
    maxlength=9 size=13>
    <input type=text name="PageDetail.rDetail[1].tbFieldName" value=""
    maxlength=9 size=13>
    <input type=text name="PageDetail.rDetail[2].tbFieldName" value=""
    maxlength=9 size=13>
    Now when I say getTbFieldName().getValues() it returns only the first
    element values in the object[] and the rest of the
    values are null.
    May be we need to create a utility method do get these values from
    requestContext.
    raju.
    ----- Original Message -----
    From: Todd Fast <toddwork@c...>
    Sent: Saturday, July 07, 2001 3:52 AM
    Subject: Re: [iPlanet-JATO] Re: Retrieving all Values from a Tiled View
    Raju.--
    I wanted to know how the getValues() method works the reason being,
    when the tiled view is NOT bound to a model, it populates all the
    fields with the same name as some thing likeI'm afraid I don't understand your point--can you please clarify? Do you
    mean "value" instead of "name"?
    What are you trying to do? What behavior are you expecting but notseeing?
    >
    Without further clarification, I can say that the setValues() methodsNEVER
    populates data on multiple rows of a (dataset) model, nor does it affect
    multiple fields on the same row. Perhaps what you are seeing is theeffect
    of default values. Model that derive from DefaulModel have the ability to
    carry forward the values set on the first row to other rows in lieu ofdata
    in those other rows. This behavior is for pure convenience and can be
    turned off, and it is turned off for the SQL-based models.
    Todd
    [email protected]

    Hi,
    I wanted to know how the getValues() method works the reason being,
    when the tiled view is NOT bound to a model, it populates all the
    fields with the same name as some thing like
    PageDetail.rDetail[0].tbFieldValue
    PageDetail.rDetail[0].tbFieldValue
    in which case, the getValues() method works fine.
    But in case where the tiled view is bound to a model, it populates
    with different field names such as,
    PageDetail.rDetail[0].tbFieldValue
    PageDetail.rDetail[1].tbFieldValue
    in this case, the getValues() doesn't work. Any soultion to this?
    We are using Moko 1.1.1.
    thanks in advance,
    raju.
    --- In iPlanet-JATO@y..., "Todd Fast" <toddwork@c...> wrote:
    Does anyone know of is there a single method to get all values of a
    display
    field in a tiled view without having to iterate through all the
    values ie
    resetTileIndex() / nextTile() approach.
    ie Something that returns an Object[] or Vector just like ND returned a
    CspVector. I tried using the getValues() methods but that allways returns
    a
    single element array containing the first element.
    (I think now, that method is used for multi selecteable ListBoxes)Actually, no. We can add this in the next patch, but for now, I'd recommend
    creating a simple utility method to do the iteration on an arbitrary model
    and build the list for you.
    Todd

  • Retrieving all values from hashmap in order you put them in

    Hi guys,
    I want to retrieve all values from a HashMap in the order I put them in.
    So I can't use the values() method that gives back a collection and iterate over that.
    Do you guys know a good way to do that ?

    You can just do something like this:
    class OrderedMap
        private final Map  m_rep = new HashMap();
        private final List m_keys = new ArrayList();
        public Object get( final Object key )
            return m_rep.get( key );
        public Object put( final Object key, final Object value )
            final Object result = m_rep.put( key, value );
            if ( result != null )
                m_keys.add( key );
            return result;
        public Object remove( final Object key )
            final Object result = m_rep.remove( key );
            if ( result != null )
                m_keys.add( key );
            return result;
        public Iterator keyIterator()
            return m_rep.iterator();
    }Then use it like this:
       for ( Iterator it = map.keyIterator(); it.hasNext(); )
           final Object value = map.get( it.next() );
       }This will be in the order you put them in. However, if you want to do this correctly, you should implement the Map interface and add all the methods. Another thing you can do is download the JDK 1.4 source, learn how they did and do it the same way for 1.2.
    R.

  • How to retrieve the values from a table if they differ in Unit of Measure

    How to retrieve the values from a table if they differ in Unit of Measure?

    If no data is read
    - Insure that you use internal code in SELECT statement, check via SE16 desactivating conversion exit on table T006A. ([ref|http://help.sap.com/saphelp_nw70/helpdata/en/2a/fa0122493111d182b70000e829fbfe/frameset.htm])
    If no quanity in result internal table
    - There is no adqntp field in the internal table, so no quantity is copied in itab ([ref|http://help.sap.com /abapdocu_70/en/ABAPINTO_CLAUSE.htm#&ABAP_ALTERNATIVE_1@1@]).
    - - Remove the CORRESPONDING, so quantity will fill the first field adqntp1.  ([ref|http://help.sap.com/abapdocu_70/en/ABENOPEN_SQL_WA.htm])
    - - Then loop at the internal table and move the quantity when necessary to the 2 other fields.
    * Fill the internal table
    SELECT msehi adqntp
      INTO TABLE internal table
      FROM lipso2
      WHERE vbeln = wrk_doc1
        AND msehi IN ('KL','K15','MT').
    * If required move the read quantity in the appropriate column.
    LOOP AT internal_table ASSIGNING <fs>.
      CASE <fs>-msehi.
        WHEN 'K15'.
          <fs>-adqnt2 = <fs>-adqnt1.
          CLEAR <fs>-adqnt1.
        WHEN 'MT'.
          <fs>-adqnt3 = <fs>-adqnt1.
          CLEAR <fs>-adqnt1.
      ENDCASE.
    ENDLOOP.
    - You could also create another table with only fields msehi and adqntp and then collect ([ref|http://help.sap.com/abapdocu_70/en/ABAPCOLLECT.htm]) the data to another table.
    Regards,
    Raymond

Maybe you are looking for