LinkedList remove

I am having problem removing data from the linked list.
My source code is
public class Foo{
    private LinkedList mList = new LinkedList();
     * Adds data to the list
    public void setData(FooBean foo){
           //add data to the list
     * returns data from the list(LIFO method)
    public FooBean getData(){
           //remove first data and return
    * removes message from the list
//I am having problem in this method
     public void removeData(){
          for(int i = 0; i < mList.size(); i++){
                 FooBean foo = (FooBean)mList.get(i);
                 if(foo.getXXX()){
                         mList.remove(i);   //removes the messages and the list size is decreased by 1.
     }When i do the above method, it gives me ArrayIndexOutofBoundException because
when the message is removed the size of the
list is also decreased.
I tried, setting i back to '0' after removing the message,
but it starts again from the top.
So i tried using i-- and so far im not getting any error
messages. Is this a good way to achieve, what i am trying to do
or is there any good method to do that?
Thanx in advance

The follwing code may help you.
import java.util.*;
public class LinkedListDemo {
     public static void main(String []args)
LinkedList<Integer> list=new
ew LinkedList<Integer>();
          list.add(20);
          list.add(7);
          list.add(11);
          list.add(54);
          list.add(89);
          list.add(98);
          list.add(77);
          list.add(32);
          list.add(67);
          list.add(26);
          list.add(3,101);
          System.out.println("Size of list: "+list.size());
          System.out.println("Contents of list: "+list);
          list.remove(5);
          list.remove(1);
          System.out.println("Size of list: "+list.size());
System.out.println("Contents of list after
er deletion: "+list);
          list.removeFirst();
          list.removeLast();
System.out.println("list size after delete first
st and last element: "+list.size());
System.out.println("list after delete first & last
st elements: "+list);
          Integer ival=list.get(0);
          list.set(6,ival);
          System.out.println("list after change: "+list);
Whatever you are talking about there makes no sense to my real question.
I know how to remove from a list and i dont even need to use the Interface List for that. LinkedList has implemented that method too.
Removing from a list is easy, but my case is remvoing inside a loop.
I think you didnt even try to read my question.

Similar Messages

  • LinkedList.remove(Object) O(1) vs O(n)

    The LinkedList class documentation says the following:
    "All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index."
    Typically one expects the remove operation from a linkedlist to be O(1). (for example [here on wikipedia|http://en.wikipedia.org/wiki/Linked_list] )
    This is in theory true however typically in the implementation of a LinkedList internally nodes (or Entry<E> in the case of the java implementation) are made that are wrappers around the actual objects inserted in the list. These nodes also contain the references to the next and previous nodes.
    These nodes can be removed from the linked list in O(1). However if you want to remove an a object from the list, you need to map it to the node to be removed. In the java implementation they simply search for the node in O(n). (It could be done without searching but this would require some mapping which requires more memory.)
    The java implementation can be seen here:
        public boolean remove(Object o) {
            if (o==null) {
                for (Entry<E> e = header.next; e != header; e = e.next) {
                    if (e.element==null) {
                        remove(e);
                        return true;
            } else {
                for (Entry<E> e = header.next; e != header; e = e.next) {
                    if (o.equals(e.element)) {
                        remove(e);
                        return true;
            return false;
        }It seems to be a common misconception that this method runs in O(1) while it actually runs in O(n). For example [here in this cheat sheet|http://www.coderfriendly.com/2009/05/23/java-collections-cheatsheet-v2/] and [in this book|http://oreilly.com/catalog/9780596527754/]. I think quite a lot of people think this methode runs in O(1). I think it should be made explicitly clear in the documentation of the class and the method that it runs in O(n).
    On a side note: the remove() operation from the LinkedList iterator does perform in O(1).

    I agree. It's not at all clear what the objection here is.
    To add to Jeff's answer: the remove operation on the LinkedListIterator is O(1) because you don't have to search for the node to unlink - the iterator already has a pointer to it.
    I tend to think of two different operations:
    - unlink - an operation specific to a linked datastructure which removes a given node from the datastructure and completes in O(1)
    - remove - an operation which searches for a given object in the data structure and then removes the node containing that object (using the unlink operation in the case of a linked datastructure). The performance of this depends on the performance of the search and unlink operations. In an unsorted linked list (e.g. the Java LinkedList) the search operation is O(n). So this operation is O(n).

  • Linked list remove method???

    hi i have made a remove method in a publication contaqiner class which links to the publicationmain.The problem is that when i run the program and try to delete a publication i get the message
    "Exception in thread "main" java.lang.IndexOutOfBoundsException: Index:1, Size:1 at java.util.LinkedList.entry<LinkedList.java:348>
    java.util.LinkedList.remove<LinkedList.java:338>
    PublicationContainer.remove<publicationcontainer.java>
    publicationmain.main<publicationmain.java>"
    What does this mean?how do i fix it so my delete method workks?can ssomeone please show me in my code???thanxs
    //this is in the publication container
    public void remove(int PubID)
    PubList.remove(PubID);
    //this is in the publicationmain class
    System.out.println ("Enter Publication ID:");
    PubID = Keyboard.readInt();
    pubdatabase.remove (PubID);

    The remove(int index) method that you are calling will try and remove the item at the index you specify.
    As the index starts at zero, if you want to remove the first element then you have to call remove(0). Calling remove(1) is beyound the possible indexes in the list, so you will get the exception thrown.
    HTH
    Chris
    hi i have made a remove method in a publication
    contaqiner class which links to the
    publicationmain.The problem is that when i run the
    program and try to delete a publication i get the
    message
    "Exception in thread "main"
    java.lang.IndexOutOfBoundsException: Index:1, Size:1
    at java.util.LinkedList.entry<LinkedList.java:348>
    java.util.LinkedList.remove<LinkedList.java:338>
    PublicationContainer.remove<publicationcontainer.java>
    publicationmain.main<publicationmain.java>"
    What does this mean?how do i fix it so my delete
    method workks?can ssomeone please show me in my
    code???thanxs
    //this is in the publication container
    public void remove(int PubID)
    PubList.remove(PubID);
    //this is in the publicationmain class
    System.out.println ("Enter Publication ID:");
    PubID = Keyboard.readInt();
    pubdatabase.remove (PubID);

  • LinkedList.isEmpty()

    Hello,
    Is there any known problem with LinkedList.isEmpty() ?
    My code verify with LinkedList.isEmpty() and after call LinkedList..removeFirst() to get the first element.
    Sometimes, the removeFirst() call throws a NoSuchElementException even if the isEmpty() returns false...
    :-|
    Thanks
    Ludovic

    Hello Everyone,
    I'm having the same trouble as this person. The only difference is my program runs for hours traversing 500+ packets per second, putting them in the LinkedList, and taking them out when the list reaches the size of 200+. It does use multiple threads. However they are executed one-at-a-time, and before each execution it does check to see if size() is > 0. And for the first 10 hours, my program is fine! But then all of a sudden I see about half a gig in my error file of:
    Exception in thread "Thread-45935" java.util.NoSuchElementException
    at java.util.LinkedList.remove(LinkedList.java:644)
    at java.util.LinkedList.removeFirst(LinkedList.java:134)
    at SipSniff.SipThread$SipParse.run(SipThread.java:241)
    at java.lang.Thread.run(Thread.java:595)
    Exception in thread "Thread-45936" java.util.NoSuchElementException
    at java.util.LinkedList.remove(LinkedList.java:644)
    at java.util.LinkedList.removeFirst(LinkedList.java:134)
    at SipSniff.SipThread$SipParse.run(SipThread.java:241)
    at java.lang.Thread.run(Thread.java:595)
    It creates a thread only in this case:
    if(packets.size() > 200) { ... creates the thread ...}
    So, I have no idea why I get that exception. It works fine for the first 10 hours. Thanks for any help.
    Elijah

  • 500 internal server error when trying to admin users

    Hi all,
    I got a problem - nothing new :-) - running Oracle Portal on 9iAS r2 on Sun Solaris.
    Whenever I try to access any page/feature related to users and/or groups, I get this as a response:
    500 Internal Server Error
    java.util.NoSuchElementException
    at java.util.LinkedList.remove(LinkedList.java:562)
    at java.util.LinkedList.removeFirst(LinkedList.java:120)
    at oracle.ldap.das.util.ConnectionManager.getContext(ConnectionPool.java:265)
    at oracle.ldap.das.util.ConnectionPool.getContext(ConnectionPool.java:86)
    at oracle.ldap.das.util.LDAPConnection.(LDAPConnection.java:62)
    at oracle.ldap.das.util.LDAPConnection.getOrCreateLDAPConnection(LDAPConnection.java:2011)
    at oracle.ldap.das.util.LDAPConnection.getOrCreateLDAPConnection(LDAPConnection.java:2002)
    at oracle.ldap.das.util.LDAPConnection.confirmLDAPSession(LDAPConnection.java:2174)
    at oracle.ldap.das.util.PartnerOIDRepository.storePartnerParameters(PartnerOIDRepository.java:245)
    at java.lang.reflect.Method.invoke(Native Method)
    at oracle.cabo.servlet.event.MethodEventHandler.handleEvent(Unknown Source)
    at oracle.cabo.servlet.event.TableEventHandler.handleEvent(Unknown Source)
    at oracle.cabo.servlet.event.TableEventHandler.handleEvent(Unknown Source)
    at oracle.cabo.servlet.event.BasePageFlowEngine.handleRequest(Unknown Source)
    at oracle.ldap.das.util.DemoPageFlowEngine.handleRequest(DemoPageFlowEngine.java:49)
    at oracle.cabo.servlet.AbstractPageBroker.handleRequest(Unknown Source)
    at oracle.cabo.servlet.PageBrokerHandler.handleRequest(Unknown Source)
    at oracle.cabo.servlet.BajaServlet.doGet(Unknown Source)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:244)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:336)
    at com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:59)
    at oracle.security.jazn.oc4j.JAZNFilter.doFilter(JAZNFilter.java:283)
    at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:523)
    at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:269)
    at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:735)
    at com.evermind.server.http.AJPRequestHandler.run(AJPRequestHandler.java:151)
    at com.evermind.util.ThreadPoolThread.run(ThreadPoolThread.java:64)
    I can't figure out what this could be due to, the app server seems to be up and running and everything else is working both in Portal and the rest of the AS.
    Does anybody has any idea?
    TIA
    Andrea

    just an update after resetting the orcladmin password to the "real" one in das.properties -- it was set to "welcome" -- i get the following while trying to access <host>:<port>/oiddas
    500 Internal Server Error
    java.lang.UnsatisfiedLinkError: no jmisc in java.library.path
    at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1349)
    at java.lang.Runtime.loadLibrary0(Runtime.java:749)
    at java.lang.System.loadLibrary(System.java:820)
    at oracle.security.misc.Checksum.(Checksum)
    at oracle.ias.repository.IASSchema$Enc.d(IASSchema.java:1279)
    at oracle.ias.repository.IASSchema.init(IASSchema.java:146)
    at oracle.ias.repository.IASSchema.(IASSchema.java:106)
    at oracle.ias.repository.SchemaManager.(SchemaManager.java:56)
    at oracle.ldap.das.util.ConnectionManager.initialise(ConnectionPool.java:324)
    at oracle.ldap.das.util.ConnectionManager.getContext(ConnectionPool.java:263)
    at oracle.ldap.das.util.ConnectionPool.getContext(ConnectionPool.java:86)
    at oracle.ldap.das.util.LDAPConnection.(LDAPConnection.java:62)
    at oracle.ldap.das.util.LDAPConnection.getOrCreateLDAPConnection(LDAPConnection.java:2011)
    at oracle.ldap.das.util.LDAPConnection.getOrCreateLDAPConnection(LDAPConnection.java:2002)
    at oracle.ldap.das.util.LDAPConnection.confirmLDAPSession(LDAPConnection.java:2174)
    at oracle.ldap.das.util.PartnerOIDRepository.storePartnerParameters(PartnerOIDRepository.java:245)
    at java.lang.reflect.Method.invoke(Native Method)
    at oracle.cabo.servlet.event.MethodEventHandler.handleEvent(Unknown Source)
    at oracle.cabo.servlet.event.TableEventHandler.handleEvent(Unknown Source)
    at oracle.cabo.servlet.event.TableEventHandler.handleEvent(Unknown Source)
    at oracle.cabo.servlet.event.BasePageFlowEngine.handleRequest(Unknown Source)
    at oracle.ldap.das.util.DemoPageFlowEngine.handleRequest(DemoPageFlowEngine.java:50)
    at oracle.cabo.servlet.AbstractPageBroker.handleRequest(Unknown Source)
    at oracle.cabo.servlet.PageBrokerHandler.handleRequest(Unknown Source)
    at oracle.cabo.servlet.BajaServlet.doGet(Unknown Source)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:244)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:336)
    at com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:59)
    at oracle.security.jazn.oc4j.JAZNFilter.doFilter(JAZNFilter.java:283)
    at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:523)
    at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:269)
    at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:735)
    at com.evermind.server.http.AJPRequestHandler.run(AJPRequestHandler.java:151)
    at com.evermind.util.ThreadPoolThread.run(ThreadPoolThread.java:64
    ...pls help me!
    andrea

  • Internal server error when trying to admin users

    Hi all,
    I got a problem - nothing new :-) - running Oracle Portal on 9iAS r2 on Sun Solaris.
    Whenever I try to access any page/feature related to users and/or groups, I get this as a response:
    500 Internal Server Error
    java.util.NoSuchElementException
    at java.util.LinkedList.remove(LinkedList.java:562)
    at java.util.LinkedList.removeFirst(LinkedList.java:120)
    at oracle.ldap.das.util.ConnectionManager.getContext(ConnectionPool.java:265)
    at oracle.ldap.das.util.ConnectionPool.getContext(ConnectionPool.java:86)
    at oracle.ldap.das.util.LDAPConnection.(LDAPConnection.java:62)
    at oracle.ldap.das.util.LDAPConnection.getOrCreateLDAPConnection(LDAPConnection.java:2011)
    at oracle.ldap.das.util.LDAPConnection.getOrCreateLDAPConnection(LDAPConnection.java:2002)
    at oracle.ldap.das.util.LDAPConnection.confirmLDAPSession(LDAPConnection.java:2174)
    at oracle.ldap.das.util.PartnerOIDRepository.storePartnerParameters(PartnerOIDRepository.java:245)
    at java.lang.reflect.Method.invoke(Native Method)
    at oracle.cabo.servlet.event.MethodEventHandler.handleEvent(Unknown Source)
    at oracle.cabo.servlet.event.TableEventHandler.handleEvent(Unknown Source)
    at oracle.cabo.servlet.event.TableEventHandler.handleEvent(Unknown Source)
    at oracle.cabo.servlet.event.BasePageFlowEngine.handleRequest(Unknown Source)
    at oracle.ldap.das.util.DemoPageFlowEngine.handleRequest(DemoPageFlowEngine.java:49)
    at oracle.cabo.servlet.AbstractPageBroker.handleRequest(Unknown Source)
    at oracle.cabo.servlet.PageBrokerHandler.handleRequest(Unknown Source)
    at oracle.cabo.servlet.BajaServlet.doGet(Unknown Source)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:244)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:336)
    at com.evermind.server.http.ResourceFilterChain.doFilter(ResourceFilterChain.java:59)
    at oracle.security.jazn.oc4j.JAZNFilter.doFilter(JAZNFilter.java:283)
    at com.evermind.server.http.ServletRequestDispatcher.invoke(ServletRequestDispatcher.java:523)
    at com.evermind.server.http.ServletRequestDispatcher.forwardInternal(ServletRequestDispatcher.java:269)
    at com.evermind.server.http.HttpRequestHandler.processRequest(HttpRequestHandler.java:735)
    at com.evermind.server.http.AJPRequestHandler.run(AJPRequestHandler.java:151)
    at com.evermind.util.ThreadPoolThread.run(ThreadPoolThread.java:64)
    I can't figure out what this could be due to, the app server seems to be up and running and everything else is working both in Portal and the rest of the AS.
    Does anybody has any idea?
    TIA
    Andrea

    Are you using another language than english ? If so, log into Portal using English and it will work. This is a known bug, apparently fixed in Portal 9.0.3

  • Byte-ranging implementation (correct version)

    I am trying to implement byte-ranging support for WebLogic 6.0.
              Unfortunately, Acrobat Reader does not understand my http response with
              ranges and crashes (or waits for something forever). Does anybody have any
              idea what might be wrong? See my code below.
              Is there a java servlet already that implements byte-ranging?
              Thank you,
              Andrei
              import java.io.*;
              import java.util.*;
              import javax.servlet.*;
              import javax.servlet.http.*;
              /** For testing only, do not look at it. */
              public class ViewFile extends HttpServlet
              public void service(HttpServletRequest req, HttpServletResponse res) throws
              ServletException, IOException
              System.out.println("ViewFile start at " + new Date());
              // Print the headers
              for (Enumeration e = req.getHeaderNames() ; e.hasMoreElements() ;)
              String name = (String)e.nextElement();
              System.out.println("> " + name + ": " + req.getHeader(name));
              // Get the file to view
              String file = req.getPathTranslated();
              // No file, nothing to view
              if (file == null)
              file = getServletContext().getRealPath("/index.html");
              System.out.println(file);
              // OK. Do the job!
              renderFileWithByteRanging(file, req, res);
              System.out.println("ViewFile finish\n");
              /** Represents a single byte range. */
              class Range
              public Range(long start, long end)
              this.start = start;
              this.end = end;
              /** The start of the range (zero based). */
              public long start;
              /** The end of the range. */
              public long end;
              * Parses the incoming ranges into a list of ranges.
              * @param ranges The string containing the ranges.
              * @param fileLength The length of the file.
              public LinkedList parseRanges(String ranges, long fileLength) throws
              Exception
              // Create an empty range list
              LinkedList result = new LinkedList();
              // Remove the "bytes=" part from the range
              int pos = ranges.indexOf('=');
              if (pos == -1)
              throw new Exception("Malformated range request: no '=' symbol");
              if ("bytes".equalsIgnoreCase(ranges.substring(pos).trim()))
              throw new Exception("Malformated range request: 'bytes'
              expected");
              ranges = ranges.substring(pos + 1);
              // Go through the range string and extract the ranges
              StringTokenizer tok = new StringTokenizer(ranges, ",");
              while (tok.hasMoreTokens())
              // Get the next range
              String rangesPart = tok.nextToken().trim();
              // Find a minus separating the range
              pos = rangesPart.indexOf('-');
              if (pos == -1)
              System.out.println("Malformated range request: no '-' symbol");
              continue;
              String strFirst = rangesPart.substring(0, pos).trim();
              String strLast = rangesPart.substring(pos + 1).trim();
              System.out.println("Parsed range: " + strFirst + "-" + strLast);
              long posFirst;
              long posLast;
              if ("".equals(strFirst)) // The first parameter is missing
              // Last n bytes. Example: -500
              posFirst = fileLength - Integer.parseInt(strLast);
              posLast = fileLength;
              else if ("".equals(strFirst)) // The second parameter is missing
              // All bytes except first n bytes. Example: 500-
              posFirst = Integer.parseInt(strFirst);
              posLast = fileLength;
              else // Full range request
              // All bytes from n to m. Example: 500-600
              posFirst = Integer.parseInt(strFirst);
              posLast = Integer.parseInt(strLast);
              // Final checks
              if (posLast > fileLength)
              posLast = fileLength - 1;
              if (posFirst >= posLast)
              posFirst = 0;
              posLast = fileLength - 1;
              // Add the range to the list
              result.addLast(new Range(posFirst, posLast));
              // That's all
              return result;
              /** Put entire file to the outpt stream. */
              public void renderFile(ServletOutputStream sos, File file) throws
              Exception
              FileInputStream fis = null;
              try
              // Create the input stream
              fis = new FileInputStream(file);
              // Allocate the 4K buffer
              byte[] buffer = new byte[4 * 1024];
              // Copy the input to the output
              int bytesRead;
              while((bytesRead = fis.read(buffer)) != -1)
              sos.write(buffer, 0, bytesRead);
              finally
              if (fis != null)
              fis.close();
              /** Put the range of the file to the output stream. */
              public void renderFileRange(ServletOutputStream sos, File file, Range
              range) throws Exception
              FileInputStream fis = null;
              try
              System.out.print("Serving range: " + range.start + "-" + range.end);
              // Create the input stream
              fis = new FileInputStream(file);
              // Skip the first bytes
              if (range.start > 0)
              long skipped = fis.skip(range.start);
              System.out.print("; skipped=" + skipped);
              // Read the requested bytes
              int rangeLength = (int)(range.end - range.start + 1);
              byte[] buffer = new byte[rangeLength];
              int bytesRead = fis.read(buffer, 0, rangeLength);
              // Write the bytes
              if (bytesRead > 0)
              sos.write(buffer, 0, bytesRead);
              System.out.println("; read=" + bytesRead);
              finally
              if (fis != null)
              fis.close();
              /* Calculate multi part content length. May not work properly. */
              public long calculateContentLength(LinkedList ranges, long fileLength,
              String contentType)
              String str;
              long length = -2;
              String boundary = "multipart-boundary";
              for (Iterator i = ranges.iterator(); i.hasNext();)
              // Get the next range
              Range range = (Range)i.next();
              // Render a new boundary
              str = "--" + boundary +
              "Content-type: " + contentType +
              "Content-range: bytes " + range.start + "-" +
              range.end + "/" + fileLength;
              length += 10 + str.length() + range.end - range.start + 1;
              str = "--" + boundary + "--";
              length += 4 + str.length();
              System.out.println("Multi-range response length: " + length);
              return length;
              * Render the specified file to the output stream.
              * The whole file is rendered in binary mode, no other output is
              allowed.
              * @param fileName The name of the file render.
              public void renderFileWithByteRanging(String fileName,
              HttpServletRequest request, HttpServletResponse response) throws IOException
              System.out.println("Serving the file: " + fileName);
              FileInputStream fis = null;
              try
              // Get the output stream
              ServletOutputStream sos = response.getOutputStream();
              // Get and set the type of the file
              String contentType = getServletContext().getMimeType(fileName);
              System.out.println("Content Type: " + contentType);
              // Open file and its length
              File file = new File(fileName);
              long fileLength = file.length();
              System.out.println("File length: " + fileLength);
              // Get ranges
              String httpRange = request.getHeader("Range");
              // Are ranges requested?
              if (httpRange == null)
              // No ranges needed
              System.out.println("No ranges. Proceed in usual way");
              response.setHeader("Accept-ranges", "bytes");
              response.setContentType(contentType);
              response.setHeader("Content-length",
              String.valueOf(file.length()));
              // Disable all kinds of caching
              // response.setHeader("Cache-Control", "no-store");
              // Render the entire file content
              renderFile(sos, file);
              else
              // Well, ranges.......
              System.out.println("Ranges are requested.");
              LinkedList ranges = parseRanges(httpRange, fileLength);
              Range range;
              // Check if we got a single range request
              if (ranges.size() == 1)
              // Yeah... a single range. Return it in the simple form
              (Apache-style)
              System.out.println("Serving a single range.");
              range = (Range)ranges.getFirst();
              sos.println("Status: 206 Partial content");
              sos.println("Content-range: bytes " + range.start + "-"
              + range.end + "/" + fileLength);
              sos.println("Content-length: " + (range.start -
              range.end + 1));
              sos.println("Content-type: " + contentType);
              sos.println();
              sos.println();
              // Render the range of the file
              renderFileRange(sos, file, range);
              else
              // Well... many ranges. Return a multipart response
              System.out.println("Serving multiple ranges.");
              // Render the multi-parse response header
              String boundary = "multipart-boundary";
              sos.println("Status: 206 Partial content");
              sos.println("Accept-ranges: bytes");
              sos.println("Content-type: multipart/x-byteranges; boundary=" +
              boundary);
              // sos.println("Content-length: " + calculateContentLength(ranges,
              fileLength, contentType));
              sos.println();
              // Go through the range list and return the
              corresponding file bits
              for (Iterator i = ranges.iterator(); i.hasNext();)
              // Get the next range
              range = (Range)i.next();
              // Render a new boundary
              sos.println();
              sos.println("--" + boundary);
              sos.println("Content-type: " + contentType);
              sos.println("Content-range: bytes " + range.start +
              "-" + range.end + "/" + fileLength);
              sos.println();
              // Render the range of the file
              renderFileRange(sos, file, range);
              // Finish the multipart response
              sos.println();
              sos.println("--" + boundary + "--");
              System.out.println("Done Serving");
              catch(FileNotFoundException fnf)
              // Send the file-not-found status if we could not open the file
              response.sendError(response.SC_NOT_FOUND);
              System.out.println("File '" + fileName + "' is not found");
              catch(Exception e)
              // Send the internal-error status for all other reasons
              if (!response.isCommitted())
              response.sendError(response.SC_INTERNAL_SERVER_ERROR,
              e.getMessage());
              e.printStackTrace();
              

    First just to clarify EBS is currently using OAF and not ADF.
    More info here:
    http://blogs.oracle.com/schan/2007/06/28#a1721
    OAF uses ADF Business Components - so if you want to use ADF to build a system that will integrate with EBS then it would make sense to go to the "ADF Tutorial for Forms/4GL Developers" tutorial.

  • In your lab05, replace instructor's Tokenizer class and MyStackQueue packag

    Objective:
    The objective of this lab is to get you some experience in processing strings character by
    character and in implementing stacks and queues in a class package.
    The programming assignment:
    In your lab05, replace instructor’s Tokenizer class and MyStackQueue package with your own.
    Requirements:
    1. You must use an array to implement your queue.
    2. You must use a linked list to implement your stack.
    3. You must use the following frame work to implement your tokenizer.
    class Tokenizer {
    private char [] Buf;
    private int cur;
    Tokenizer(String infixExpression) {
    Buf = infixExpression.toCharArray();
    cur = 0;
    Token nextToken() {
    1. Skip blanks.
    2. if (cur>=Buf.length) return null;
    3. If the next character is a digit, keep reading until a non-digit is read.
    Convert the string of digits into an integer.
    String Digits = new String(Buf, start, len);
    int num = Integer.valueOf(Digits).intValue();
    Create and return an operand.
    4. Otherwise, use the next character to create and return an operator.
    class Tokenizer {
         private char[] Buf;
         private int cur;
         Tokenizer(String infixExpression) {
              Buf = infixExpression.toCharArray();
              cur = 0;
         Token nextToken() {
              int bufLength = Buf.length;
              Object obj = null;
              // ignore blank space
              while (cur < bufLength && Buf[cur] == ' ') {
                   cur++;
              // if given string having only space return null
              if (cur >= Buf.length)
                   return null;
              StringBuilder value = new StringBuilder();
              // Iterate through each element of string array and construct an string
              // for consecutive digits
              while (cur < bufLength && Buf[cur] <= '9' && Buf[cur] >= '0') {
                   value.append(Buf[cur]);
                   cur++;
              // if digits are there convert all digits as an integer value and create
              // operand
              if (value.length() > 0) {
                   obj = new Operand(Integer.parseInt(value.toString()));
              // if at cur position no digit is present then create operand with the
              // same non digit value
              else {
                   obj = new Operator(Buf[cur]);
                   cur++;
              return ((Token) (obj));
    package StackAndQueue;
    public class Queue {
         private int front;
         private int rear;
         private int capacity;
         private Object S[];
         public Queue() {
              front = 0;
              rear = -1;
              capacity = 100;
              S = new Object[capacity];
         public boolean isEmpty() {
              return S[front] == null;
         public void enqueue(Object obj) {
              int insertionPoint = (rear + 1) % capacity;
              if (S[insertionPoint] == null) {
                   S[insertionPoint] = obj;
                   rear = insertionPoint;
              } else {
                   System.out.println("Queue capacity is full");
         public Object dequeue() {
              if (S[front] != null) {
                   Object obj = S[front];
                   S[front] = null;
                   front = (front + 1) % capacity;
                   return obj;
              } else {
                   System.out.println("Queue is empty");
                   return null;
         public String toString() {
              StringBuilder state = new StringBuilder("[");
              for (int i = front; i < capacity; i++) {
                   if (S[i] != null) {
                        state.append(S[i] + ", ");
              for (int i = 0; i < front; i++) {
                   if (S[i] != null) {
                        state.append(S[i] + ", ");
              if (state.length() > 1) {
                   state.delete(state.length() - 2, state.length() - 1);
              state.append("]");
              return state.toString();
    package StackAndQueue;
    import java.util.LinkedList;
    import java.util.List;
    public class Stack {
         List<Object> linkedList = null;
         public Stack() {
              linkedList = new LinkedList<Object>();
         public boolean isEmpty() {
              return linkedList.size() == 0;
         public void push(Object obj) {
              linkedList.add(obj);
         public Object pop() {
              int topIndex = linkedList.size() - 1;
              if (topIndex >= 0) {
                   Object obj = linkedList.get(topIndex);
                   linkedList.remove(topIndex);
                   return obj;
              } else {
                   return null;
         public Object top() {
              int topIndex = linkedList.size() - 1;
              if (topIndex >= 0) {
                   return linkedList.get(topIndex);
              } else {
                   return null;
    }

    So you want us to do what ?
    Edited by: sabre150 on Oct 9, 2012 3:17 PM
    Cross posted to http://www.coderanch.com/t/594750/Servlets/java/your-lab-replace-instructor-Tokenizer .

  • Implementing a Queue ADT

    Hi. I'm trying to implement an adt Queue. I have the following program which is only in its infancy but I think I'm going in the right direction.
    import java.util.*;
    public class Queue
         private LinkedList list = new LinkedList(); 
         public void put(Object v)
              list.addFirst(v);
         public Object getLast()
              return list.removeLast();  
         public Object getFirst()
              return list.removeFirst();
         public boolean isEmpty()
              return list.isEmpty();  
         public static void main(String[] args)
              Queue queueList = new Queue();   
              for(int i = 0; i < 10; i++)     
              queueList.put(Integer.toString(i));   
              while(!queueList.isEmpty())
              System.out.println(queueList.getFirst());
              System.out.println("Now Popping");
              for(int i = 0; i < 3; i++)     
              queueList.getLast();
              while(!queueList.isEmpty())
              System.out.println(queueList.getFirst());
         } Basically the program writes in 10 values to the queue and then prints it out. Then it should pop off the first 2. I'll add user input later when I get the darn thing working but I'm getting the following output...
    9
    8
    7
    6
    5
    4
    3
    2
    1
    0
    Now Popping
    Exception in thread "main" java.util.NoSuchElementException
    at java.util.LinkedList.remove(LinkedList.java:575)
    at java.util.LinkedList.removeLast(LinkedList.java:139)
    at Queue.getLast(Queue.java:26)
    at Queue.main(Queue.java:53)
    Press any key to continue...
    Any pointers to where I'm going wrong.
    McGumby..

    You have a loop which removes the first element until the list is empty. You then try to remove 3 more elements using getLast(), but the list is empty. The API for [url http://java.sun.com/j2se/1.4.2/docs/api/java/util/LinkedList.html#getLast()]getLast() method in the [url http://java.sun.com/j2se/1.4.2/docs/api/java/util/LinkedList.html]LinkedList class states:
    Throws:
    NoSuchElementException - if this list is empty.
    That's what is happening...

  • Display popup inside applyResult method of ovs?

    Hi,
    I have implemented an object value selector for a field.
    Now what I want to do is to display a popup window when   the user selects a row inside ovs popup (ie. inside the applyResult method).
    The popup window (with ok and cancel buttons) is being displayed, but when I try to destroy it inside the event handler for a popup ok or cancel buttons, the exception gets thrown. The exception says something about No item found on the list??
    I guess it has something to do with trying to display it inside applyresult method?
    The details:
    Popup is being displayed inside applyResult method of a customController (MaterialIndexCust)
         IWDWindowInfo windowInfo = wdComponentAPI.getComponentInfo().findInWindows("ConfirmExpandSpecWindow");
         IWDWindow window = wdComponentAPI.getWindowManager().createModalWindow(windowInfo);
         window.setWindowPosition(WDWindowPos.CENTER);
         window.setTitle("Question");
         wdContext.currentPopupElement().setWindowInstance(window);
         window.show();
    Here's the code from the event handler which is from the same custom controller :
            IWDWindow window = wdContext.currentPopupElement().getWindowInstance();
            window.destroyInstance();
    The actual event had to be defined in another controller.
    I've tried these things with IWDConfirmationDialog as well  as my custom dialog.
    Any help is appreciated.
    Regards,
    Ladislav

    Here's the exception:
    java.util.NoSuchElementException
         at java.util.LinkedList.remove(LinkedList.java:579)
         at java.util.LinkedList.removeFirst(LinkedList.java:131)
         at com.sap.tc.webdynpro.clientserver.window.ApplicationWindow.popModalWindow(ApplicationWindow.java:162)
         at com.sap.tc.webdynpro.clientserver.window.WebDynproWindow.doClose(WebDynproWindow.java:400)
         at com.sap.tc.webdynpro.clientserver.window.Window.doClose(Window.java:195)
         at com.sap.tc.webdynpro.clientserver.window.ApplicationWindow.handle(ApplicationWindow.java:288)
         at com.sap.tc.webdynpro.clientserver.window.ApplicationWindow.handleWindowEvents(ApplicationWindow.java:260)
         at com.sap.tc.webdynpro.clientserver.cal.AbstractClient.executeTasks(AbstractClient.java:149)
         at com.sap.tc.webdynpro.clientserver.session.ApplicationSession.doProcessing(ApplicationSession.java:299)
         at com.sap.tc.webdynpro.clientserver.session.ClientSession.doApplicationProcessingStandalone(ClientSession.java:707)
         at com.sap.tc.webdynpro.clientserver.session.ClientSession.doApplicationProcessing(ClientSession.java:661)
         at com.sap.tc.webdynpro.clientserver.session.ClientSession.doProcessing(ClientSession.java:229)
         at com.sap.tc.webdynpro.clientserver.session.RequestManager.doProcessing(RequestManager.java:152)
         at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doContent(DispatcherServlet.java:62)
         at com.sap.tc.webdynpro.serverimpl.defaultimpl.DispatcherServlet.doPost(DispatcherServlet.java:53)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.runServlet(HttpHandlerImpl.java:390)
         at com.sap.engine.services.servlets_jsp.server.HttpHandlerImpl.handleRequest(HttpHandlerImpl.java:264)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:347)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.startServlet(RequestAnalizer.java:325)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.invokeWebContainer(RequestAnalizer.java:887)
         at com.sap.engine.services.httpserver.server.RequestAnalizer.handle(RequestAnalizer.java:241)
         at com.sap.engine.services.httpserver.server.Client.handle(Client.java:92)
         at com.sap.engine.services.httpserver.server.Processor.request(Processor.java:148)
         at com.sap.engine.core.service630.context.cluster.session.ApplicationSessionMessageListener.process(ApplicationSessionMessageListener.java:33)
         at com.sap.engine.core.cluster.impl6.session.MessageRunner.run(MessageRunner.java:41)
         at com.sap.engine.core.thread.impl3.ActionObject.run(ActionObject.java:37)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sap.engine.core.thread.impl3.SingleThread.execute(SingleThread.java:100)
         at com.sap.engine.core.thread.impl3.SingleThread.run(SingleThread.java:170)

  • Remove object from Linkedlist?

    Hello,
    I built this function to return the object with the lowest cost variable, and remove this object from the linkedlist.
    The method does not always seem to return the object with the lowest cost. I wondered if the problem was because I removed the object being returning?
    Could anyone see the problem?
    Thanks
    Node lowestState(LinkedList list){
    Node object = (Node) list.get(0);
    int index = 0, cost = object.getCost();
    for(int i = 1; i < list.size(); i++){
    object = (Node) list.get(i);
    int testCost = object.getCost();
    if(testCost < cost){
    cost = testCost;
    index = i;
    list.remove(index);
    return object;
    }

    get() must traverse the links until it finds the given one.
    So get() behaves O(n), like the whole traversal.
    import java.util.*;
    public class llt {
    static LinkedList li = new LinkedList();
    static int LIMIT=64*1024;
    public static void main(String args[]) {
         for(int i=0;i<LIMIT;i++) li.add(new Integer(i%7 * (i%3) + (i%5)));
         for(int k=0;k<4;k++) doit();
    static void doit() {
    int i;
    int sum=0;
    long t0=System.currentTimeMillis();
         for(i=0;i<li.size();i++) {
              sum += ((Integer) li.get(i)).intValue();
    long t1=System.currentTimeMillis();
         for(ListIterator lii =li.listIterator(0);lii.hasNext();) {
              sum -= ((Integer) lii.next()).intValue();
    long t2=System.currentTimeMillis();
         System.out.println((t2-t1) + " " + (t1-t0) + " " + sum);
    0 27594 0
    0 27719 0
    0 28359 0
    0 27391 0

  • Problems with add() and remove() in my Doubly Circular Linkedlist code

    I have been working on this code for 6 hours and some how it won't remove correctly when the list has 0,2,4 elements.
    It will attempt to remove element at index 0 but actually removed 4. I thought it was the reference problem at first, so i did something to my add() method so that it reference head to tail, tail to head. But still, the code doesn't work.
    The problem seem to be how to remove the element at index 0. If anyone has any ideas, please let me know.
    Add:
    public void add(T item) {
              if (isEmpty()){     
                   Node<T> n = new Node<T> (null,item,null);     
                   head = n;
                   tail = n;
                   head.setNext(tail);
                   head.setPrev(tail);
                   tail.setNext(head);
                   tail.setPrev(head);
              else{
                   Node<T> n = new Node<T> (tail,item,head);
                   n.getPrev().setNext(n);
                   tail=n;
                   head.setPrev(tail);
                   tail.setNext(head);
              size++;
         }Remove:
    public T removeAt(int index) {
              Node<T> target = getNode(index);
              //System.out.println(target.getValue());
              if (index>size()||index<0){
                   throw new IllegalArgumentException
                        ("Can't remove anything out of the list.");
              if (isEmpty()){
                   throw new NoSuchElementException
                        ("Can't remove from empty list.");
              }else {
                   if (target.getNext().equals(target.getPrev())){
                        target.getNext().setNext(null);
                        target.getPrev().setPrev(null);
                   }else{
                   System.out.println("target prev: "+ target.getPrev().getValue());
                   System.out.println("target: " + target.getValue());
                   System.out.println("target next: "+ target.getNext().getValue());
                   target.getPrev().setNext(target.getNext());
                   target.getNext().setPrev(target.getPrev());
                   size--;
              return target.getValue();
         }

    size won't ever reach -1 since it won't -1 if isEmpty() returns true in getNode().
    The procedure is, if I can get the node, i will try to remove it, if i can't even get it, nothing will run in removeAt (idx) except the first line.
    public T removeAt(int index) {
              Node<T> target = getNode(index);
              if (size()==1){
                   head=tail=null;
                   size=0;     
                   return null;
              }else if (size()==2){
                   if (index==0)                      // first but not the last.
                        target.getNext().setPrev(null);
                        target.getNext().setNext(null);
                   if (index==1)                   // last but not the first.
                       target.getPrev().setPrev(null);
                        target.getPrev().setNext(null);
              }else{
                        System.out.println("target prev: "+ target.getPrev().getValue());
                        System.out.println("target: " + target.getValue());
                        System.out.println("target next: "+ target.getNext().getValue());
                        target.getNext().setPrev(target.getPrev());
                        target.getPrev().setNext(target.getNext());
                   size--;          
              return target.getValue();
         }

  • How to print the content of LinkedList int[] and LinkedList LinkedList ?

    Hi guys, its been a long time since i posted here, and now im coming back to programming using java. My problem is, how can i print the content of the list?
    Example:
    LinkedList<int[]> list = new LinkedList<int[]>;
    int[] input = {1,2,3,4,5};
    int[] input2 = {2,32,43,54,65};
    list.add(input);
    list.add(input2);
    how can i print all the content of the linkedlist?
    Please help me..I know its a dumb question but i really dunno how.
    here is the code:
    import java.util.LinkedList;
    import java.util.Scanner;
    import java.util.Arrays;
    public class Test{
         static void printThis(String[] in){
              System.out.print("Value: ");
              for(int i = 0;i<in.length;i++){
                   System.out.print(in[i] + " ");
              System.out.println();
         static void reset(String[] val){
              for(int i = 0;i<val.length;i++){
                   val[i] = "";
         public static void main(String[] args){
              LinkedList<String[]> list = new LinkedList<String[]>();
              LinkedList<String> listTrans = new LinkedList<String>();
              System.out.print("Enter the number of records: ");
              Scanner s = new Scanner(System.in);
              int numOfRecords = s.nextInt();
              System.out.print("Enter the number of records per run: ");
              s = new Scanner(System.in);
              System.out.println();
              int numOfRecordsInMemory = s.nextInt();
              String[] getData = new String[numOfRecords];
              String[] transferData = new String[numOfRecordsInMemory];
              int numOfRuns = 0;
              int counter = 0;
              for(int i = 0;i<numOfRecords;i++){
                   counter++;
                   System.out.print("Enter value number " + counter + ": ");
                   Scanner scan = new Scanner(System.in);
                   getData[i] = scan.next();
                   listTrans.add(getData);
              if(getData.length%numOfRecordsInMemory == 0){
                   numOfRuns = getData.length/numOfRecordsInMemory;
              }else if(getData.length%numOfRecordsInMemory != 0){
                   numOfRuns =(int)(getData.length/numOfRecordsInMemory)+ 1;
              System.out.println();
              System.out.println("Number of Runs: " + numOfRuns);
         int pass = 0;
         System.out.println("Size of the main list: " + listTrans.size());
         while(listTrans.size() != 0){
              if(listTrans.size() >= numOfRecordsInMemory){
                   for(int i = 0;i<numOfRecordsInMemory;i++){
                        transferData[i] = listTrans.remove();
                   System.out.println("Size of the list: " + listTrans.size());
                   printThis(transferData);
                   System.out.println();
                   Arrays.sort(transferData);
                   list.add(transferData);
                   reset(transferData);
              }else if(listTrans.size() < numOfRecordsInMemory){
                   pass = listTrans.size();
                   for(int k = 0;k<pass;k++){
                        transferData[k] = listTrans.remove();
                   System.out.println("Size of the list: " + listTrans.size());
                   printThis(transferData);
                   System.out.println();
                   Arrays.sort(transferData);
                   list.add(transferData);
                   reset(transferData);
    //This is the part that is confusing me.
    //im trying to print it but its not working.
              System.out.println("Size of the next list: " + list.size());
    //          for(int i = 0;i<list.size();i++){
    //                    System.out.println();
    //               for(int j = 0;j<list.get(i)[j].length();j++){                    
    //                    System.out.print(list.get(i)[j] + " ");

    Here's the funnest, mabye clearest way you could do it: Use 2 Mappers
    package tjacobs.util;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.List;
    import tjacobs.Arrays;
    public class Mapper <T>{
         public static interface MappedFunc<T> {
              void map(T value);
         public Mapper(T[] vals, MappedFunc<T> function) {
              this (new Arrays.ArrayIterator<T>(vals), function);
         public Mapper(Iterator<T> iterator, MappedFunc<T> function) {
              while (iterator.hasNext()) {
                   function.map(iterator.next());
         public static void main(String[] args) {
              String[] s = new String[] {"a","b", "c", "abc", "ab"};
              MappedFunc<String> func = new MappedFunc<String>() {
                   public void map(String s) {
                        if (s.toLowerCase().startsWith("a")) {
                             System.out.println(s);
              Mapper m = new Mapper(s, func);
    }

  • Remove 1st & 2nd lines in 1st file, and 1st line in 2nd file. I want the headers to be the first line after the script runs!

    I have two files that look like this (Notepad++):
    In the first file, which has a date as a name and always ends in 'COV', I want to remove the 1st & 2nd lines.  All lines end in LF (LineFeed).  In the 2nd file, which has a date as a name and always ends in 'RSK', I want to remove the 1st line. 
    Basically I want only the headers.  I'm working with the code below.  I've tried several different iterations of
    reader.ReadLine().Skip(1);
    reader.ReadLine().Skip(2);
    reader.ReadLine().Skip(3);
    It never really gives me what I want, so I can't tell what's going on here.  I guess I'm missing something simple, but I don't know what.  Any ideas, anyone?
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Diagnostics;
    namespace ConsoleApplication1
    class Program
    static void Main(string[] args)
    string sourceDirectory = @"C:\Users\rshuell\Desktop\Downloads\Files";
    try
    var txtFiles = Directory.EnumerateFiles(sourceDirectory);
    foreach (string currentFile in txtFiles)
    if (currentFile.Contains("COV"))
    var items1 = new LinkedList<string>();
    using (var reader = new StreamReader(currentFile))
    reader.ReadLine().Skip(2); // skip 2lines
    string line;
    while ((line = reader.ReadLine()) != null)
    items1.AddLast(line.Replace("\"", ""));
    File.WriteAllLines(currentFile, items1);
    else
    var items2 = new LinkedList<string>();
    using (var reader = new StreamReader(currentFile))
    reader.ReadLine().Skip(1); // skip one line
    string line;
    while ((line = reader.ReadLine()) != null)
    items2.AddLast(line.Replace("\"", ""));
    File.WriteAllLines(currentFile, items2);
    catch (Exception ex)
    Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.

    Call the ReadLine() twice if you want to skip the first two lines. Each call results in a single line being read:
    static void Main(string[] args)
    string sourceDirectory = @"C:\Users\rshuell\Desktop\Downloads\Files";
    try
    var txtFiles = Directory.EnumerateFiles(sourceDirectory);
    foreach (string currentFile in txtFiles)
    if (currentFile.Contains("COV"))
    var items1 = new LinkedList<string>();
    using (var reader = new StreamReader(currentFile))
    reader.ReadLine(); //read line 1
    reader.ReadLine(); //read line 2
    string line;
    while ((line = reader.ReadLine()) != null)
    items1.AddLast(line.Replace("\"", ""));
    File.WriteAllLines(currentFile, items1);
    else
    var items2 = new LinkedList<string>();
    using (var reader = new StreamReader(currentFile))
    reader.ReadLine(); // skip one line
    string line;
    while ((line = reader.ReadLine()) != null)
    items2.AddLast(line.Replace("\"", ""));
    File.WriteAllLines(currentFile, items2);
    catch (Exception ex)
    Calling the Skip method on the already read string returned by the ReadLine() method won't help you at all here. By the time you call the Skip method the line has already been read from the file. You must call the ReadLine() method for a new line being read.
    Hope that helps.
    Please remember to close your threads by marking helpful posts as answer and please start a new thread if you have a new question.

  • For each loop and modification of a LinkedList

    When going thourhg my LinkedList with a for each loop, I want to do a modification. I just saw that it cast a ConcurrentModification Exception, so it seems I can't do that.
    How should I do then? I don't want to go through all the list each time an object is removed, I want it to restart where it stopped.

    Not the best solution but something like thisshould work:
    if( linkedList.get(i) == "modification")No: don't compare Strings with the == operator.
    http://access1.sun.com/FAQSets/newtojavatechfaq.html#9
    You are correct, must be .equals() my bad.

Maybe you are looking for