Paasing an ArrayList as an argument

In an assignment i am doing i have to pass an arraylist from one swing window to another and i thought i could pass them similar to as you would with methods with the line below:
ColBookCar win = new ColBookCar(customers,cars);
and then my BookCar window would take the ArrayLists as arguments, as below:
public ColBookCar(ArrayList customers, ArrayList cars)
but this is not compiling at all! I was wondering if someone could tell me how to perform this or a better way to pass the arraylist from one window to another to be accessed in the second one. Thank You!

The error is:
M:\CC438\Implementation2\ColBookCar.java:291: ')' expected
          ColBookCar GangEditor = new ColBookCar(ArrayList customers, ArrayList cars);
^
1 error
Tool completed with exit code 1

Similar Messages

  • This is a stumper of a problem

    This is quite a specialised problem and i hope someone can help me
    I am writing a jsp web page to display information from a ldap directory. It works fine except i need to specify where the program is to search the ldap tree. When i specify no location i.e. "" the program works perfectly but when i specify a location such as i.e. "cn=Radiation,cn=Documentation" tomcat returns an error that doesnt exactly explain whats happening the main error line reads
    org.apache.jasper.JasperException: ld.Connection.getDocument(Ljava/lang/String;)Ljava/util/ArrayList;The must stumping part of this problem is that the program runs in jbuilder when i specify a location but not on tomcat, i find this strange as jbuilder runs it in tomcat to run it!!!
    The code for the jsp page is this
    <?xml version="1.0" encoding="utf-8"?>
    <?xml-stylesheet type="text/xsl" *******"?>
    <%@ page contentType="application/xml" %>
    <%@ page import="java.util.*" %>
    <%@ page import="javax.naming.*" %>
    <%@ page import="ld.*" %>
    <%@ page import="biz.osoft.escies.*" %>
    <%
    long start = System.currentTimeMillis();
    %>
    <html xml:lang="en">
    <head>
      <title>Escies Conference Documents</title>
      <identifier>*****</identifier>
      <date><%=new java.sql.Date(System.currentTimeMillis())%></date>
      <contributor>webmaster</contributor>
      <subject>Titles and description of Documents</subject>
      <description>Titles and description of Documents</description>
      <script type="text/javascript">
            function PrintAuthor(anAuthor)
                alert (anAuthor);
         function PrintDescription(aDescription)
                alert (aDescription)
         function PrintKeywords(aKeyword)
                alert (aKeyword)
      </script>
    <style type="text/css" >
    div.scroll {height: 3ex; overflow: auto;}
    </style>
    </head>
    <body>
      <h1>Documents</h1>
      <br clear="all" />
      <index>
    <%
    Connection ldap = new Connection();
    String DocumentLocation = new String("cn=Irradiation,cn=Radiation,cn=Documentation");
    ArrayList doc = ldap.getDocument(DocumentLocation);
    String ldapLocation = new String();
    String ldapLoc= new String();
    String nextLdapLocation = new String();
    String ldapPosition = new String();
    %>
    <%/*StringTokenizer st = new StringTokenizer(ldapPosition,",");
    ArrayList a = new ArrayList();
    while (st.hasMoreTokens())a.add(st.nextToken());
    Object [] backwards = a.toArray();
    int l = backwards.length;
    String forwards = "";
    for (int j = l-1; j>=0; j--){
         backwards [j] = ((String) backwards [j]).substring(3);
         forwards += backwards[j];
         if (j>0){forwards += " ";}
         }*/%>
    <%
    for (int n=0; n <  doc.size(); n++){
         LDAPDocument identifier = (LDAPDocument)doc.get(n);
            ldapLoc=identifier.getCnString();
            ldapLoc=ldapLoc.substring((ldapLoc.indexOf(",")+1));
         if(doc.size()-1>=(n+1)){
         LDAPDocument nextIdentifier = (LDAPDocument)doc.get(n+1);
            nextLdapLocation=nextIdentifier.getCnString();
            nextLdapLocation=nextLdapLocation.substring((nextLdapLocation.indexOf(",")+1));
         }else{nextLdapLocation="";}
         //ldapGroup=identifier.getCnString();
         //ldapGroup=ldapGroup.substring((ldapGroup.indexOf(",")+1),ldapGroup.indexOf(ldapPosition)-1);
         ldapPosition=ldapLoc;
         StringTokenizer st = new StringTokenizer(ldapPosition,",");
         ArrayList a = new ArrayList();
         while (st.hasMoreTokens())a.add(st.nextToken());
         Object [] backwards = a.toArray();
         int l = backwards.length;
         String forwards = "";
         for (int j = l-1; j>=0; j--){
              backwards [j] = ((String) backwards [j]).substring(3);
              forwards += backwards[j];
              if (j>0){
                   forwards += " ";
    %>
    <%if (ldapLoc.matches(ldapLocation)!=true){%>
    <group heading ="<%=forwards%>">
    <item>
      <table>
    <col width = "55%" />
    <col width = "10%" />
    <col width = "15%" />
    <col width = "15%" />
    <col width = "5%" />
        <tr>
          <th>Document Title</th>
          <th>Document Author</th>
          <th>Document Description</th>
          <th>Document Keywords</th>
          <th>Document Location</th>
        </tr>
    <%}%>
    <%ldapLocation=ldapLoc;%>
         <tr><div class="scroll">
             <td valign="top">
              <%=ldap.convertToXML(identifier.getIdentifier())%>
             </td>
             <td valign="top">
              <a href="javascript:PrintAuthor('<%=ldap.convertToXML(identifier.getAuthor())%>')">Author</a>
             </td>
             <td valign ="top">
              <a href="javascript:PrintDescription('<%=ldap.convertToXML(identifier.getDescription())%>')">Description</a>
             </td>
             <td valign ="top">
              <a href="javascript:PrintKeywords('<%=ldap.convertToXML(identifier.getKeywords())%>')">KeyWords</a>
             </td>
             <td valign = "top">
              <a href="<%=ldap.convertToXML(identifier.getLocation())%>">GO</a>
             </td>
         </div>
         </tr>
    <%if (ldapLoc.matches(nextLdapLocation)!=true){%>
    </table>
    </item>
    </group>
    <%}%>
    <%//ldapLocation=ldapLoc;%>
    <%
    %>
      </index>
    <%
    ldap.close();
    %>
    </body>
    </html>and the class that the jsp page is using is this
    package ld;
    import java.util.*;
    import java.util.ArrayList;
    import java.io.*;
    import javax.naming.*;
    import javax.naming.directory.*;
    import javax.naming.NamingException;
    public class Connection{
       public DirContext ctx = null;
       public Connection() throws javax.naming.NamingException{
       Hashtable env = new Hashtable();
       env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
       env.put(Context.PROVIDER_URL, "*********");
       env.put(Context.SECURITY_AUTHENTICATION,"simple");
       env.put(Context.SECURITY_PRINCIPAL,"*****"); // specify the username
       env.put(Context.SECURITY_CREDENTIALS,"*****");           // specify the password
       try{
         ctx = new InitialDirContext(env);
       }catch(Exception a){System.out.println(a);}
       public ArrayList getDocument() throws NamingException{
         int n=0;
         ArrayList document = new ArrayList();
         String[] attrIDs = {"cn"};
         SearchControls ctls = new SearchControls();
         ctls.setReturningAttributes(attrIDs);
         ctls.setReturningObjFlag(true);
         ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
         String filter = "(documentIdentifier=*)";
         try{
           NamingEnumeration e = ctx.search("", filter, ctls);
           System.out.println("Search performed");
           document = formatResults(e);
           System.out.println("finished formatresults method");
           Collections.sort(document, new DocumentComparator());
           System.out.println("finished sorting alphabethically");
         }catch(Exception f){System.out.println("exception caught "+f);}
         for (n=0;n<document.size();n++){
            System.out.println(document.get(n));
         System.out.println("closing context");
         ctx.close();
       return document;
       public ArrayList getDocument(String argument) throws NamingException{
            int n=0;
            ArrayList document = new ArrayList();
            String[] attrIDs = {"cn"};
            SearchControls ctls = new SearchControls();
            ctls.setReturningAttributes(attrIDs);
            ctls.setReturningObjFlag(true);
            ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
            String filter = "(documentIdentifier=*)";
            try{
              NamingEnumeration e = ctx.search(argument, filter, ctls);
              System.out.println("Search performed");
              document = formatResults(e ,argument);
              System.out.println("finished formatresults method");
              //Collections.sort(document, new DocumentComparator());
            }catch(Exception f){System.out.println("fault line 68 : "+f);}
            //for (n=0;n<document.size();n++){
            //   System.out.println(document.get(n));
           System.out.println("closing context");
            ctx.close();
          return document;
       public ArrayList formatResults (NamingEnumeration eneration, String argument) throws Exception{
         ArrayList document = new ArrayList();
         int n=0;
         System.out.println("Starting while loop line 81");
         try{
         while (eneration.hasMore()){
         System.out.println("line 87");
          String aVal = eneration.nextElement().toString();
          System.out.println("line 89");
          aVal = aVal.substring(0,aVal.indexOf(":"));
          System.out.println(aVal);
          aVal +=",";
          aVal +=argument;
          System.out.println(aVal);
          System.out.println("line 91");
          document.add(getIdentifier(aVal));
          System.out.println("line 93");
          System.out.println(document.size());
          for (n=0; n<document.size(); n++){
             System.out.println(document.get(n));
          }catch (NamingException e){
          e.printStackTrace();
          }System.out.println("ending while loop line 101");
          System.out.println("number of locations in document - : "+document.size());
          return document;
       public ArrayList formatResults (NamingEnumeration eneration) throws Exception{
         ArrayList document = new ArrayList();
         int n=0;
         System.out.println("Starting while loop line 81");
         try{
         while (eneration.hasMore()){
         System.out.println("line 87");
          String aVal = eneration.nextElement().toString();
          System.out.println("line 89");
          aVal = aVal.substring(0,aVal.indexOf(":"));
          System.out.println(aVal);
          System.out.println("line 91");
          document.add(getIdentifier(aVal));
          System.out.println("line 93");
          System.out.println(document.size());
          for (n=0; n<document.size(); n++){
             System.out.println(document.get(n));
          }catch (NamingException e){
          e.printStackTrace();
          }System.out.println("ending while loop line 101");
          System.out.println("number of locations in document - : "+document.size());
          return document;
       public void close() throws NamingException{
         if(ctx != null)ctx.close();
       public LDAPDocument getIdentifier(String baseDN) throws NamingException{
          String TEST = new String();
          int test = 0;
          String ldapLoc = new String();
          LDAPDocument doc = new LDAPDocument();
          System.out.println(baseDN);
          Attributes attrs = ctx.getAttributes(baseDN);
          NamingEnumeration e = attrs.getIDs();
          System.out.println("while loop starting line 125");
          while (e.hasMore()){
             try{
                String id = e.nextElement().toString();
                doc.setCnString(baseDN);
                if (id.equals("cn"))
                   doc.setName(attrs.get(id).get().toString());
                if (id.equals("documentIdentifier"))
                   doc.setIdentifier(attrs.get(id).get().toString());
                if (id.equals("description"))
                   doc.setDescription(attrs.get(id).get().toString());
                if (id.equals("documentAuthor"))
                   doc.setAuthor(attrs.get(id).get().toString());
                if (id.equals("keyWords"))
                   doc.setKeywords(attrs.get(id).get().toString());
                if (id.equals("documentLocation")) {
                   doc.setLocation(attrs.get(id).get().toString());
             }catch(Exception b){System.out.println("exception is : "+b);}
             System.out.println("while loop finished line 144");
         }return doc;
       public static String convertToXML(String s) {
        return convertToXML(s, false);
      public static String convertToXML(String s, boolean replaceLineEndings) {
        if (s != null) {
          s = s.replaceAll("&", "&");
          s = s.replaceAll("<", "<");
          s = s.replaceAll(">", ">");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          s = s.replaceAll("�", "�");
          if (replaceLineEndings)
            s = s.replaceAll("\n", "<br />");
        return s;
    class DocumentComparator implements Comparator {
         java.text.Collator collator = java.text.Collator.getInstance();
         public int compare (Object d1, Object d2){
            return collator.compare(((LDAPDocument) d1).getLdapLocation(),((LDAPDocument) d2).getLdapLocation());
    }I know this is a tough problem but even if i get a post saying that someone cant see anything wrong it would help

    oh and this is the full error list given by tomcat
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: ld.Connection.getDocument(Ljava/lang/String;)Ljava/util/ArrayList;
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:248)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:260)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2415)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:170)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:432)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:386)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:534)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:530)
         at java.lang.Thread.run(Thread.java:536)
    root cause
    javax.servlet.ServletException: ld.Connection.getDocument(Ljava/lang/String;)Ljava/util/ArrayList;
         at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:533)
         at org.apache.jsp._136_jsp._jspService(_136_jsp.java:214)
         at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:137)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:204)
         at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:295)
         at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:241)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:260)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2415)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:170)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:432)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:386)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:534)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:530)
         at java.lang.Thread.run(Thread.java:536)
    Apache Tomcat/4.1.18does this mean anything to anyone cos it means nothing to me
    cheers

  • Passing vectors

    Does anyone have any examples of passing a vector from method to method?

    I agree with the principle that you might need access to methods not defined in List but in this case I really don't think it's necessary. What could you use the Vector for other than a dynamic size list? Why would you need to call setSize()? By saying that the method takes a List you have documented the concept that the method does something with a list, not necessarily a Vector. It's confusing to specify a Vector in the method because it leads you to believe that it does some Vector specific stuff to it, which it most likely doesn't.
    Regardless, Vector shouldn't be used because it's now a legacy class. Let's all join the 21st century and start using ArrayList :-). And don't give me the, "but Vector's synchronized and Arraylist isn't" argument.
    List list = Collection.synchronizedList(new ArrayList());

  • ArrayList Error on Index

    This is my code;
    * Main2.java
    * Created on 09 February 2007, 14:40
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package testing;
    * @author Administrator
    import java.sql.*;
    import java.util.ArrayList;
    import java.util.ListIterator;
    * @author Administrator
    public class Main2 {
        Connection conn=null;
        Statement stmt=null;
        ResultSet rsBankName=null;
        int valid,invalid,total;
        /** Creates a new instance of Main */
        public Main2() {
            connectOracle();
            readCards(2007,1,31);
            //System.out.println(checkDate(""));
         * @param args the command line arguments
        public void connectOracle(){
            try {
                Class.forName("oracle.jdbc.driver.OracleDriver");
                conn = DriverManager.getConnection("jdbc:oracle:thin:@IP:SID", "user", "pwd");
                stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {}
        public void readCards(int year,int month,int day){
            String bankCode="";
            ArrayList<String> bname=new ArrayList<String>(10);
            try {
                rsBankName=stmt.executeQuery("select bank_code,bank_name from bank");
                rsBankName.first();
                do{
                    bname.add(rsBankName.getInt("bank_code"),rsBankName.getString("bank_name"));
                }while(rsBankName.next());
            } catch (SQLException ex) {
                ex.printStackTrace();
            ListIterator li=bname.listIterator();
            while(li.hasNext()){
                System.out.println(li.next());
        public static void main(String[] args) {
            new Main2();
    }And I am getting this Stack trace
    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
    at java.util.ArrayList.add(ArrayList.java:367)
    at testing.Main2.readCards(Main2.java:60)
    at testing.Main2.<init>(Main2.java:36)
    at testing.Main2.main(Main2.java:71)
    I search for it on the net, it say it has a bug and it was version 1.2 and I am using the new version of JDK 1.6.
    Any idea what is going wrong.

    D'OH!!
    You can't add an element at a specific index unless
    there is already something at that index ? WTF? This
    is strange behavior, What is even odder is that you can expand by one with "add", just not greater than that.
         ArrayList<Integer> thingies = new ArrayList<Integer>(10);
         for(int i = 0; i< 10; i++ ) {
             thingies.add( i, i );
         System.out.println( thingies );works, but
         ArrayList<Integer> thingies = new ArrayList<Integer>(10);
         for(int i = 9; i>0; i-- ) {
             thingies.add( i, i );
         System.out.println( thingies );does not.
    even though I will say that
    there are other classes you could use instead. Try a
    HashMap<Integer,String> Or if the size is fixed, use an array.

  • Printing an ArrayList

    Hi there,
    I need a little bit of help to print some text. I am able to print out a simple line of text and it works fine, but I need to be able to print out the contents of an ArrayList. At the moment I have a Page() class that implements Prinatable. By default there is a print() mehtod. In htis print method is where I set my page size and also the text that need to be printed. The method
    g2d.drawString(titleText, (int) titleX, (int) titleY);is the method that actually prints the text. titleText is just a regular String.
    If I want to print the contents of an ArrayList I'll have to iterate over it somehow and extract he data that I want to print.
    The method g2d.drawString() can take an argument AttributedCharacterIterator instead of string and it will iterate over this and print out what is in it.
    Is there anyway I can add the data in my ArrayList to the AttributedCharacterIterator? Because I tried to iterate through my ArrayList and add iter.next() to AttributedCharacterIterator but I get a classCastExcetpion.
    It would be great to hear from anyone who has printed from an Arraylist before. I have posted the code form my Page() class below.
    Thanks,
    Chris
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
    throws PrinterException {
    Graphics2D g2d = (Graphics2D) graphics;
    g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    g2d.setPaint(Color.black);
    String titleText = "E-vote Ballot";
    Font titleFont = new Font("tahoma", Font.BOLD, 36);
    FontMetrics fontMetrics = g2d.getFontMetrics ();
    double titleX = (pageFormat.getImageableWidth () / 2) - (fontMetrics.stringWidth (titleText) / 2);
    double titleY = 3 * POINTS_PER_INCH;
    g2d.drawString(titleText, (int) titleX, (int) titleY);
    return (PAGE_EXISTS);
    }

    I need to be able to print out the contents of an ArrayListDo you want all the items together or each item on it's own line?
    for the former,
    * returns a String containing al's elements, space-separated.
    String arrayListToString( ArrayList al )
       String s = "";
       for (Object o :  al)
          s += o + " ";
       s = s.substring(0,s.length() - 1); // cut off that last space we added
       return s;
    }and then
    g2d.drawString(arrayListToString( yourList ), posX, posY); for the latter,
    * Draws the elements of al to the screen as strings.  The first element goes at
    * posX , posY, the second goes at  posX, posY + vertOffset,  &c
    void drawArrayList( ArrayList al , Graphics g , int posX, int posY, int vertOffset)
       int offset = 0;
       for (Object o : al)
          g.drawString( o, posX  , posY + offset);
          offset += vertOffset;
    }

  • How can i send user defined Object as a argument to the MBean methods in authentication provider to create user?

    I developed our own Authentication, Identity Assertion & Authorization providers
    for weblogic 8.1 SP1. In the authenticator MBean i have one method which takes
    user defined object as a argument and returns a user defined object. i am able
    to call all the methods which takes java objects(for example: String, int, ArrayList,
    HashMap, Etc...) as a argument and returns also a java object but when i user
    any user defined object then it gives exception. if in the argument i used user
    defined object then it is not able to call that method telling NoSuchMethodException.
    Is there any way to use user defined object as an argument to MBean method?
    can anyone please help us as we r in the final stage of the project?
    Thanks
    Lakshmi

    "Lakshmi Padhy" <[email protected]> wrote in message
    news:3fc2f50c$[email protected]..
    >
    I developed our own Authentication, Identity Assertion & Authorizationproviders
    for weblogic 8.1 SP1. In the authenticator MBean i have one method whichtakes
    user defined object as a argument and returns a user defined object. i amable
    to call all the methods which takes java objects(for example: String, int,ArrayList,
    HashMap, Etc...) as a argument and returns also a java object but when iuser
    any user defined object then it gives exception. if in the argument i useduser
    defined object then it is not able to call that method tellingNoSuchMethodException.
    >
    Is there any way to use user defined object as an argument to MBeanmethod?
    >
    I seem to remember that jmx only supports scalar datatypes. Ask in the
    weblogic.developer.interest.management newsgroup.

  • A bunch of ArrayLists

    Overview
    My program needs to store 11 different types of data (numbered 1 through 12, skipping 5, although I may find a way to fill this gap soon). Each type of data needs to have a bunch of entries of undeterminate size (ArrayList), but I know there will always be 11 different types of data. I figured instead of having 11 different ArrayList variables and 11 getters, 11 setters, and 11 removers, I could just store them all in an array of some sort, and then only have 1 getter/setter/remover/etc which takes an argument of what data type it is.
    Problem
    Problem is, I'm not exactly sure what to use to group these ArrayLists together. I tried an array, but it complains about the generic typing:
    ArrayList<Resource> resList[] = new ArrayList<Resource>[13]();
    or any combination/order of [13] and () and it always complains "Cannot create a generic array of ArrayList<Resource> or "Cannot convert from ArrayList<Resource> to ArrayList<Resource>[]"
    Solution
    Using basic google skills, I discovered I could use:
    ArrayList resList[] = new ArrayList[12];
    essentially just dropping the type...
    and then loop through the 13 new ArrayList<Resource>();
    Resulting Problem
    Then when I go to add one of the datatypes to its respective data type ArrayList
    resList[Resource.PATH].add(new Path());
    it warns me: "...Type Safety... raw type ArrayList... should be Parameterized"
    it also says the same thing, somewhat surprisingly, when I generalize the path data type back down to Resource:
    resList[Resource.PATH].add((Resource)new Path());
    since I did declare each arraylist of type <Resource>. Yet it makes the same complaint.
    Conclusion
    There's basically 4 possible outcomes to this that I can think up.
    1) (Mostly desirable) There is a solution to my Type Safety warning.
    2) (Undesirable) use @SuppressWarnings
    3) An alternative to bunching them in arrays (I had a glance at Arrays.asList, but wasn't so sure about it)
    4) (Undesirable) just leave them as 11 different ArrayList variables and make them public.
    Thanks in advance,
    -IsmAvatar

    @musicalscale, thanks, I think. Is this just creating
    an ArrayList of ArrayLists? Because I don't think
    that's appropriate here because the 11 data types are
    unchanging (until I fill in the gap at 5, in which
    case it's simply a matter of slight recoding which
    I'm more than happy to do).Yes, it's an ArrayList of ArrayLists. It will get rid of the generics warnings. If you don't plan on changing the size of the outer ArrayList, then you don't have to change it. Only your one class that keeps the private ArrayList of ArrayLists will have direct access to the outer list (unless you code it otherwise). So, you don't have to worry that someone else will mess up the list.
    Or, after you create the initial list of lists, store the private reference as an unmodifiable List:
    private final List< List < Resource > > resList;// In your constructor (or another method):
    // create tempResList with generics as described,
    // then set the instance variable as
    resList = Collections.unmodifiableList(tempResList);Then even your local class can't add or remove things from the outer list (they can still modify the inner lists).
    As for HashMap, I guess it doesn't matter that the
    order may change, since we have the key paired with
    it. But is HashMap also dynamically resizable? Maybe
    I'm just blind to the internal workings.Yes, a HashMap is dynamically resizable. Since you have a key, yes, the order doesn't matter (there is also a TreeMap that keeps the keys sorted, but you don't really need that for your stated purposes). You can make an unmodifiable Map similar to how you make an unmodifiable List.

  • Memory Leak in ArrayList ?

    Dear all,
    When I went thru the implementation of ArrayList, it just appeared to me that there can be a memory leak in the ensureCapacity method, which allocated new memory... The code is as below.
    *Increases the capacity of this <tt>ArrayList</tt> instance, if*
    necessary, to ensure that it can hold at least the number of elements
    *specified by the minimum capacity argument.*
    *@param   minCapacity   the desired minimum capacity*
        public void ensureCapacity(int minCapacity) {
         modCount++;
         int oldCapacity = elementData.length;
         if (minCapacity > oldCapacity) {
    *Object oldData[]* = elementData;
             int newCapacity = (oldCapacity * 3)/2 + 1;
                 if (newCapacity < minCapacity)
              newCapacity = minCapacity;
                // minCapacity is usually close to size, so this is a win:
                elementData = Arrays.copyOf(elementData, newCapacity);
        }Dont we need to make null the reference of oldData, as oldData = null, so that gc can reclaim the memory used by the old elementData, soon after the array copy (Arrays.copyOf) ??
    Please suggest if my understanding is wrong..
    Thanks & Regards
    Joby

    JOBY1985 wrote:
    Dear all,
    When I went thru the implementation of ArrayList, it just appeared to me that there can be a memory leak in the ensureCapacity method, which allocated new memory... The code is as below.
    *Increases the capacity of this <tt>ArrayList</tt> instance, if*
    necessary, to ensure that it can hold at least the number of elements
    *specified by the minimum capacity argument.*
    *@param   minCapacity   the desired minimum capacity*
    public void ensureCapacity(int minCapacity) {
         modCount++;
         int oldCapacity = elementData.length;
         if (minCapacity > oldCapacity) {
    *Object oldData[]* = elementData;
             int newCapacity = (oldCapacity * 3)/2 + 1;
             if (newCapacity < minCapacity)
              newCapacity = minCapacity;
    // minCapacity is usually close to size, so this is a win:
    elementData = Arrays.copyOf(elementData, newCapacity);
    }Dont we need to make null the reference of oldData, as oldData = null, so that gc can reclaim the memory used by the old elementData, soon after the array copy (Arrays.copyOf) ??No we don't need to set any thing to 'null'. The reference 'elementData' is update by the Arrays.copyOf() invocation and whatever it used to reference is then only referenced by oldData and when the block in which the reference 'oldData' is declared exits there will be no reference to the original array so it is eligible for GC.
    >
    Please suggest if my understanding is wrong..Your understanding is wrong.
    >
    Thanks & Regards
    JobyEdited by: sabre150 on Oct 20, 2009 1:20 PM

  • Method to return ArrayList or Vector doesn't work, why?

    Hi, I try to return a ArrayList or Vector from a method but it does not work.. wondering why and how to fix it? Thanks:)
    class Class1{
          public static main(...){
              Class2 test = new Class2();
              ArrayList<String> resp = test.class2method(...);
              if(resp.get(4).equals(...)) {        
    class Class2{
        public ArrayList class2method(int NumInt1, int NumInt2, ...) {
           ArrayList<String> arrayTesting = new ArrayList<String>(13);
           responses.set(2, Integer.toString(NumInt1));
           responses.set(3, Integer.toString(NumInt2));
           responses.set(4, Integer.toString(NumInt3));
           responses.set(5, Integer.toString(NumInt4));
           responses.set(6, Integer.toString(NumInt5));
           return responses;
    }

    what is responses? don't you want to return
    arrayTesting?yes, responses is arrayTesting, sorry did notmention
    that.what do you mean? is the code you posted a typo or
    what you actually have in your code?It's more than 1000 lines codes so I decided not to posted them but here is part of them. My point is that i tried to return a ArrayList or Vector even with a simple code, it does not work. Thanks for your help.
    public class DemoScript {
        public DemoScript() throws IOException {
            // register the shutdown hook
            Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    System.out.println("close prog");
                     endApp();
        public void endApp() {
            System.out.println("done!");
            System.exit(0);
         public static void main(String[] args) {
              Parameters p = new Parameters();
              VMF vm = null;
                   //Elements: [0]time, [1]MsgType, [2]NumInt1, [3]NumInt2, [4]NumInt3, [5]NumInt4, [6]NumInt5, [7]NumLong,
                   //               [8]String1, [9]String2, [10]String3, [11]String4, [12]String5
    //               ArrayList<String> responses = new ArrayList<String>(13);
              try {
                   MyScript my = new MyScript();
                   if(args.length == 5) {
                       p.vmHost = args[1]; p.vmPort = Integer.parseInt(args[2]);
                       p.guiHost = args[3]; p.guiPort = Integer.parseInt(args[4]);
                  } else if(args.length == 4) {
                       p.vmHost = args[1]; p.vmPort = Integer.parseInt(args[2]); p.guiHost = args[3];
                  } else if(args.length == 3){
                       p.vmHost = args[1]; p.vmPort = Integer.parseInt(args[2]);
                  } else if(args.length == 2){
                       p.vmHost = args[1];
                  } else {
                       System.out.println("Usage: java MyScript [port #] [voice mail hostname] <voice mail socket #> <GUI hostname> <GUI socket #>");
                       System.out.println("Default: <voice mail socket #> = "+p.vmPort+", <GUI hostname> = "+p.guiHost+", <GUI socket #> = "+p.guiPort);
                       System.exit(-1);
    //               String hostname;
                   //int port;
                   /* Check for input arguments */
                   //if(args[0] != null){
                   //     port = Integer.parseInt(args[0]);
                   //     hostname = args[1];
                   //} else {
                   //     port = 2000;
                   //     hostname = "10.0.0.228";
                   //System.out.println("tews");
                   vm = new VMF(p.vmHost, p.vmPort, p.guiHost, p.guiPort);
                   vm.logon();
                   //vm.portAbort(4);/*
                   vm.portCapture(3, 0);
                   //vm.portAbort(4);/*
                   //vm.portOnhook();
                   //vm.portOffhook();
                   ////vm.portStop(3);  //to stop a port current operation
                   //vm.portWaitring(); //vm will not resp until port detects ring
                   //vm.portOffhook();
                   //vm.portGetdigits(5, 7);
                   //vm.portDialdigits("201");
                   //for(int i=0;i<100000000;i++);
                   //vm.portCallprogress(3, 0, 10);
                   //System.out.println("d");
                   //for(int i=0;i<1000000;i++);
                   //vm.portGetdigits(5, 7);
                   //vm.portRecordfile(30, 1, "\\\\kanapak.ctlinc.local\\VMfiles\\test.wmv");
                   //vm.portClearDTMF();
                   //vm.portPlayfile("\\\\kanapak.ctlinc.local\\VMfiles\\test.wmv");
                   //vm.portPlayprompt(2);
                   //vm.portSpeaknumber(3845);
                   //vm.portSpeakdigits("1639123478866478909");//75655656566657867867*");
                   //vm.portExternalcall(4, "933");
                   ArrayList<String> response = vm.portInternalcall(2, "201");
                   System.out.println(response.get(4));
                   if(response.get(4).equals("DONE")) {
                        vm.portPlayprompt(1); vm.portPlayprompt(2);
                   } else if(response.get(4).equals("GONE")) {
                   vm.portSpeakttsstring("hello. This will create ");//a project with all of the proper SWT and JFace imports. Version 4.1.1 latest build released (SWT visual inheritance, enhanced SWT GridLayout support, non-visual beans, custom !!!SWT widgets, code generation enhancements, expose property, etc.)");
                   vm.portRelease();
                   vm.logoff();
                   vm = new VMF(p.vmHost, p.vmPort, p.guiHost, p.guiPort);
                   vm.logon();
                   vm.portCapture(Integer.parseInt(args[0]), 0);
                   vm.portOnhook();
                   vm.portOffhook();
                   //          vm.portGetdigits(5, 7);
                   //vm.portRecordfile(30, 1, "\\\\kanapak.ctlinc.local\\VMfiles\\test.wmv");
                   //vm.portClearDTMF();
                   //vm.portPlayfile("\\\\kanapak.ctlinc.local\\VMfiles\\test.wmv");
                   vm.portPlayprompt(86);
                   //          vm.portSpeaknumber(3845);
                   //vm.portSpeakdigits("1639123478866478909");//75655656566657867867*");
                   //vm.portExternalcall(4, "933");
                   //vm.portInternalcall(9, "82045");
                   //vm.portSpeakttsstring("hello. This will create");// a project with all of the proper SWT and JFace imports. Version 4.1.1 latest build released (SWT visual inheritance, enhanced SWT GridLayout support, non-visual beans, custom !!!SWT widgets, code generation enhancements, expose property, etc.)");
                   vm.portRelease();
                   vm.logoff();
              } catch (IOException e) {
                   e.printStackTrace();
              } catch (InterruptedException e) {
                   //catch "STOP PORT"
                   vm.logoff();
    class VMF {
        public ArrayList<String> portInternalcall(int rings, String dial_string) {
             if (logon_status == 0) {
                   System.err.println("Error: logon required");
                   logoff();closeAndExit();
              } else if (capture_status == 0) {
                   System.err.println("Warning: portCapture required");logoff();closeAndExit();
              } else if (rings <1 || rings >999 || !checkDigits(dial_string)) {
                   System.err.println("Warning: portInternalcall( [1-999] , \"[0-9,A-D,F,P,a-d,f,p,*,#]\" )");
             breakString(dial_string);
             ostruct.write("", "IVR", "123", 188, captured_port, rings, 0, 0, 0, 0, str1, str2, str3, str4, str5);
             sendToGUI("s", "", "IVR", "123", "188", Integer.toString(captured_port),
                       Integer.toString(rings), "0", "0", "0", "0", str1, str2, str3, str4, str5);
             readStream();
             recToGUI("r", Integer.toString(MsgType),Integer.toString(NumInt1),Integer.toString(NumInt2),
                        Integer.toString(NumInt3),Integer.toString(NumInt4),Integer.toString(NumInt5),
                        Integer.toString(NumLong),String1,String2,String3,String4,String5);
              responses.set(2, Integer.toString(NumInt1)); responses.set(3, Integer.toString(NumInt2));
              responses.set(4, Integer.toString(NumInt3)); responses.set(5, Integer.toString(NumInt4));
              responses.set(6, Integer.toString(NumInt5));
              return responses;
    }

  • List.clear() outside of List finalList = new ArrayList(); will delete element in finalList?

    Hello all!
    I am using 3 ArrayLists.
    the first is List<String>
    the second is List<String[]>
    and the third is a list of those lists List<List>
    I use the first list to get the string I need, but I use the second for String.split.
    I then need to keep a list of these to use, so I need the third List.
    After adding the second list to the list of lists I want to clear it so I can set up the next list to be added, but if I do list.clear(); it will delete everything in that list.
    If I do not clear it, it is fine.
    At first I wasn't sure if it was my fault, because I'm not sure if I ever had to do that before, so I made a test case that yields the result if I change the element outside.
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package javaapplication1;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    * @author Konrad
    public class JavaApplication1 {
         * @param args the command line arguments
        String a;
        List<String> j = new ArrayList<>();
        public JavaApplication1()
            a();
        public void a()
            a = "ADASDSADSA";
            j.add(a);
            a = null;
            System.out.println(j);
        public static void main(String[] args) throws SQLException {
            JavaApplication1 a = new JavaApplication1();
    If I change a = null to a = ""; it still yields the original a = "ADASD......";
        protected List<String> list = new ArrayList<>();
        protected List<String[]> list2 = new ArrayList<>();
        protected List<List> finalList = new ArrayList<>();
      finalList.add(list2);
                     //list2.clear();
    With this I yield an empty array element, even though my array elements exist.  I tried using multiple lists and I just had multiple empty elements.
    So again I'm not sure if I did something wrong, or is this a bug?  Since my test case worked, I'm confused.
    Thanks!
    ~KZ

    After adding the second list to the list of lists I want to clear it so I can set up the next list to be added, but if I do list.clear(); it will delete everything in that list.
    Correct - you are just working with multiple references to the SAME set of objects.
    Use 'remove' to remove an element from a list and then 'add' to add it to the other list.
    See the Javadocs for the 'remove' method of the List interface
    http://docs.oracle.com/javase/6/docs/api/java/util/List.html#remove(int)
    remove
    E remove(int index)
    Removes the element at the specified position in this list (optional operation). Shifts any subsequent elements to the left (subtracts one from their indices). Returns the element that was removed from the list.   
    Parameters: 
    index - the index of the element to be removed 
    Returns: 
    the element previously at the specified position 
    Throws: 
    UnsupportedOperationException - if the remove operation is not supported by this list 
    IndexOutOfBoundsException - if the index is out of range (index < 0 || index >= size())

  • How do I create a Dynamic java.sql.Date ArrayList or Collection?

    I Have a MySQL table with a Datetime field with many values inserted.
    I want to know which is the Best way to capture all the Inserted DB values inside a Dynamic Array.
    I get errors that state that I should use Matching data-types, and plus I don't know how to create or fill a Dynamic Date ArrayList/Collection.
    Please Help, I need this urgently...

    package pruebadedates;
    import java.sql.*;
    * @author J?s?
    public class ClaseDeDates {
        /** Creates a new instance of ClaseDeDates */
         * @param args the command line arguments
        public static void main(String[] args) {
            java.sql.Date aDate[] = null;       
            Connection con = null;
            Statement stmt = null;
            ResultSet rs = null;
            try{
                Class.forName("com.mysql.jdbc.Driver").newInstance();
                con = DriverManager.getConnection("jdbc:mysql://localhost/pruebafechas", "root", "picardias");
                    if(!con.isClosed()){
                    stmt = con.createStatement();
                    stmt.executeQuery ("SELECT dates FROM datestable");
                    rs = stmt.getResultSet();
                        while (rs.next())
                        aDate[] = rs.getDate("dates");
            catch(Exception e)
               System.out.println(e);
            //System.out.println(aDate);     
    }Hi, There is my code and the errors that I get are:
    found : java.sql.Date
    required: java.sql.Date[]
    aDate = rs.getDate("dates");
    Actually I have No idea as How to get a Result set into an ArrayList or Collection. Please tell me how to do this Dynamically. I have like 25 records in that Database table, but they will grow, so I would really appreciate to know the code to do this. I suspect my problem is in the bolded part of my code.
    Thank you very much Sir.

  • Why wouldn't indexOf ArrayList function work?

    I can't post EXACT code since it's company information. I will try to replicate it here though so please bare with me.
    BEAN:
    public class Product {
    String name;
    String soldDate;
    Long id;
    // set and get functions for each also
    }Product are in a database, the bean above represents what is in the database record.
    ArrayList productList = new ArrayList();
    // Initialized with Product objects.
    // Function deletes a product based on an id
    // gets record from database and converts it to a Product object
    Product prodToDelete = myDBAccess.get(id);
    int index = productList.indexOf(prodToDelete);
    productList.remove(index);I get an IndexOutOfBoundsException thrown because the index comes back as -1. I printed out all the values and everything is the same.

    "Searches for the first occurence of the given argument, testing for equality using the equals method."
    Oh so in Product class I need a function
    public boolean equals(Product p){
    ... // test each attribute?
    }

  • Web Service Method that returns an ArrayList

    Hi guys,
    I have to create a web service method that returns an ArrayList, but it's not working. My problem is:
    With the "@XmlSeeAlso" annotation, my client prints the result, but the ArryaList is not from java.util, it's from org.me.calculator so I can't use it.
    If I remove this annotation, I get no result, with this error message on Tomcat 6:
    [javax.xml.bind.JAXBException: class java.util.ArrayList nor any of its super class is known to this context.]
    I'm a newbie, and trying to understand web services (I read some posts here, but didn't get the point, from its answers), but this problem I just can't figure out how to solve....
    WEb Service
    package org.me.calculator;
    import java.io.Serializable;
    import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    import java.util.*;
    import java.util.ArrayList;
    import javax.xml.bind.annotation.XmlSeeAlso;
    * @author eduardo.domanski
    @WebService()
    @XmlSeeAlso({java.util.ArrayList.class}) // With this, I can see the result on client, but, the ArrayList is an org.me.calculator.ArrayList class.... Strange...
    public class CalculatorWS {
        @WebMethod(operationName = "valores")
        public ArrayList valores(@WebParam(name = "a") int a,
                           @WebParam(name = "b") int b) {
            ArrayList teste = new ArrayList();
            ArrayList a1 = new ArrayList();
            a1.add(a);
            a1.add(b);
            ArrayList a2 = new ArrayList();
            a2.add(a+b);
            a2.add(a-b);
            teste.add(a1);
            teste.add(a2);
            return  teste; 
    }CLient
    package org.me.calculator.client;
    import java.io.*;
    import java.net.*;
    import java.util.ArrayList;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class ClientServlet extends HttpServlet {
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet ClientServlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet ClientServlet at " + request.getContextPath() + "</h1>");
            try { // Call Web Service Operation
                org.me.calculator.CalculatorWSService service = new org.me.calculator.CalculatorWSService();
                org.me.calculator.CalculatorWS port = service.getCalculatorWSPort();
                // TODO initialize WS operation arguments here
                int i = 8;
                int j = -6;
                // TODO process result here
                ArrayList result = (ArrayList) port.valores(i, j);
                out.println("Result = " + result);
            } catch (Exception ex) {
                System.out.println(ex);
            // TODO handle custom exceptions here
            out.println("</body>");
            out.println("</html>");
            out.close();
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            processRequest(request, response);
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            processRequest(request, response);
    }THank you all,
    Eduardo
    Edited by: EduardoDomanski on Apr 23, 2008 4:40 AM

    I forgot to say that, when I try to return an ArrayList of an object, for example, ClassA, which is on the package org.me.classes, on my Server App, the ArrayList is returned, but the objects are from type org.me.calculator.ClassA. It should be from org.me.classes.ClassA, right?
    This package also exists on my client App, to use the object, but as the returned type is from another package, I can't even cast it. I tried some annotations @Xml... but it failed.
    Packages
    ServerApp
    org.me.calculator
    CalcWS.java
    org.me.classes
    ClassA.java
    Client App
    org.me.classes
    ClassA.java
    The return from my method should be an ArrayList of org.me.classes.ClassA, but when I print it, on client, it's from org.me.calculator.ClassA.
    Does anybody knows, or had the same problem?
    Thanks,
    Eduardo

  • Parsing a txt doc and using the text to put into an arraylist

    so i have a sample doc like this:
    add name hairy; mass 4; species bird
    sort mass
    save myaddresses.txt
    so i would like to have a scanner read the above text and parse for words name, mass and species where it would store the word after it into an arraylist. there is a argument which reads the txt file. i also use a delimited to seperate out the variables.
    import java.util.*;
    import java.io.*;
    public class Animallog {
    public static void main (String [] args)throws Exception
    Animal a = new Person();
    name = a.getname();
    mass = a.getmass();
    species= a.getspecies();
    ArrayList <Animal> list = new ArrayList<Animal>();
    i=0;
    list.get(i).SetName();
    list.get(i).SetMass();
    list.get(i).SetSpecies();
    i++;
    break;
    File f = new File (args[0]);
    Scanner interactionsinput = new Scanner(f);
    interactionsinput.useDelimiter(";");
    nameinput = interactionsinput.next();
    if (nameinput.equalsIngnoreCase("name"))
    massinput = interactionsinput.next();
    if (massinput = equalsIgnoreCase("mass"))
    speciesinput = interactionsinput.next();
    if (speciesinput.equalsIgnoreCase("species"))
    so here i'm totally lost i'm surpose to parse this sample and put the data into the arraylist and a set of information for a single animal.
    }

    :o]
    Indeed, and it is important to notice the "like me" he added to it. If he had said Java to be too hard for newbies, there'd be enough proof that it isn't, because then there'd be no experts.

  • Type parameter in 'add' method of 'ArrayList'

    My little application utilizes an object of type 'ArrayList', especially because this class enables the size increment of the list by successive actions after its creation. http://java.sun.com/javase/6/docs/api/ shows that I can use the method '*add(E e)*' for this purpose.
    The IDE I use is 'NetBeans IDE 6.5'.
    My object of type 'ArrayList' is multi-dimensional and to build it up, I make use of a re-entering method. At the end of this last, one can thus see :
         chaîneCible.add(descendant);
         return (chaîneCible);In 'chaîneCible.add(...',
    1) if I don't write the type E of the object e to append ('descendant')
    - the pre-compiler doesn't grumble : It does not underline the statement in red
    although the type of method parameter, own to 'descendant', is missing - e.g. 'String'.
    - the debugger grumbles :
    Note: C:\Documents and Settings\Me\My documents\ApplicPrograms\Application7\src\package\NoeudàCaseàCocher.java uses unchecked or unsafe operations.
    Note: Recompile with -Xlint:unchecked for details.2) if I add the type E of the object e to append - e.g. 'BigDecimal' - then
    - the pre-compiler grumbles :
    - It underlines the statement in red.
    - "Missing ;" + "Cannot find symbol" + "Symbol : variable String" + "location : ..."
    Confusion : It takes the type for an argument !
    - although the API stipulates that it is mandatory to specify the type of the parameter in front of it.
    3) I don't know when anymore, the compiler returned
    Class 'ArrayList' - method 'add'
    automatic casting of a 'String' into an 'Object' is refuted at compilationWhy cannot I specify the type E of the argument e, as the API requires ?
    Thanks in advance.

    Dear DrClap,
    Here is an intermediate source code (121 lines) of my original code file (1145 lines) which is working well, except this arrayList.*add(E e)* issue.
    You see here the declaration of the ArrayList, the code where I add entries to the ArrayList, the code where I try to "add the type E ...
    By writing *add(E e)*, I am simply using the syntax mentioned in http://java.sun.com/javase/6/docs/api/
    I guarantee that the code that I filtered out is not relevant to my arrayList.*add(E e)* issue.
    It is going on a parser that inserts String data from an auxiliairy file at the time of parsing the principal source file (chaîneSource), to generate a target file (chaîneCible).
    {code}
    package arbreformtarif;
    import java.util.ArrayList;
    import java.math.BigDecimal;
    class NoeudàCaseàCocher
    String dénomFournis;
    FormTarif donnéesàTéléch_CB;
    Object[] formTarif;
    private static Object[] formTarif_Libellés;
    private static byte langue = 0;
    private BigDecimal[] consommParticul;
    NoeudàCaseàCocher (Object[] data_TariefForm,
    String gewest,
    String naam_Aanbod,
    FormTarif dataToDownload_CB,
    { formTarif = data_TariefForm;
    donnéesàTéléch_CB = dataTeDownloaden_CB;
    private ArrayList assocLibellésAuxDonnées(Object[] chaîneSource)
    { byte nbreEléments = (byte) chaîneSource.length;
    ArrayList chaîneCible = new ArrayList(nbreEléments);
    Object descendant = null;
    for (int nbreBoucle = 0; nbreBoucle < nbreEléments; nbreBoucle++)
    { Object élément = chaîneSource[nbreBoucle];
    if (élément instanceof String)
    { switch (...) //
    { case 0:
    switch (...)
    { case 1:
    dénomFournis = (String) élément;
    break;
    case 2:
    switch (...)
    { case 1:
    moisDApplication = (String) élément;
    break;
    case 2:
    break;
    default:
    break;
    case 3:
    break;
    default:
    break;
    case 1:
    switch (...)
    { case 0:
    switch (...)
    { case 0:
    break;
    break;
    default:
    descendant = (String) élément;
    } else
    { if (élément instanceof Boolean)
    descendant = (Boolean) élément;
    } else
    { if (élément instanceof BigDecimal)
    descendant = (BigDecimal) élément;
    } else
    { if (élément instanceof Object[])
    switch (...)
    { case 0:
    élément = ((Object[])formTarif[iCA[0][1]]);
    break;
    case 2:
    switch (...)
    { case 0:
    chaîneCible.add(((Object[])formTarif_Libellés[langue])[3]); // Always a String
    break;
    default:
    break;
    default:
    break;
    default:
    descendant = (ArrayList)assocLibellésAuxDonnées((Object[]) élément);
    } else
    { if (élément == null)
    /* Note: C:\Documents and Settings\Charles\Mijn documenten\Applic Program\Java\CostComp_HomeElectric_2\
    * src\arbreformtarifàtélécharger\Noeudà2CasesàCocher.java uses unchecked or unsafe operations.
    * Note: Recompile with -Xlint:unchecked for details.
    chaîneCible.add(descendant);
    return (chaîneCible);
    {code}
    Remember that
    - 'élément' and 'descendant' are, depending of the momentaneous case, of type String, BigDecimal, Boolean, Object[] or null.
    - 'assocLibellésAuxDonnées' is a re-entering method.
    Thanks

Maybe you are looking for