Lists or Arrays

Hi,
I'm reading in a very complex XML file that has this format -- very simplified.
<Report>
    <rule id="1">
        <testedObject/>
        <testedObject/>
    </rule>
    <rule id="2">
        <testedObject/>
        <testedObject/>
        <testedObject/>
        <testedObject/>
    </rule>
    <rule id="3"/>
</Report>I was thinking the best way to do this is that I'll create a Parser, Report and TestedObject class. The question is how to keep track of the multiple Rules, and testedObjects? I was thinking of creating a List, but than an array would be easier. Is there a better way to do this without having to write everything to an external database?
This is some of what I have so far ... if at all possible, I rather keep everything in memory so that I can do manipulations and calculations before writting everything out to a database in a new format.
Parser.java
               NodeList rules = doc.getElementsByTagName("Rule");
               for (int s = 0; s < rules.getLength(); s++)
                    Element rule = (Element)rules.item(s);
                    // ReportEntry
                    ReportEntry ore = new ReportEntry(rule); ReportEntry.java
               (bunch of setters)
               NodeList Results = rule.getElementsByTagName("testedObject");
          if (Results.getLength() > 0) {
               for (int s = 0; s < Results.getLength(); s++)
                 Element result = (Element)Results.item(s);
                Rule or = new Rule(result);
          }

Thank you for the feedback.
I'll take a look at JAXB and XMLBeans. I've also contacted the developer to see if I can get the schema. I'm sure I can't come up with it, it's a very very convoluted xml file.
The final destination of the tool is going to be a database, so I'm not using that as an interim holding area. I just wanted to do what I needed before connecting and dumping the rows, which sounds like I can without having too much issues.
The reason I said that an array wold be easier is that if I parse the XML I know exactly how many time the element is repeated, so I can create the array to the size I need, (i.e. no trim needed), but that was before I know about JAXB or XMLBeans.

Similar Messages

  • Casting List to Array of Unknown SubClass

    How do I cast a java.util.List to an array of a unknown subclass of a known parent class?
    Parent[] parents = someMethod();
    // someMethod returns ChildA[] or ChildB[] both extends Parent and are unknown to this method
    List list = new Vector();
    for (int i=0;i<parents.length;i++) {
      if (parents.someBoolean)
        list.add(parents[ i ]);
    return (Parent[])list.toArray(?????);
    // return (Parent[])list.toArray(new Parent[]{});
    // Not of the child type, will cause ClassCastException
    // return (Parent[])list.toArray(parents);
    // Correct type, but uses size of parents which is potentially too big.Any way to do this without reflection?

    But is is that at any given time, the array contains all elements of
    either ChildA or ChildB? If not, I'm not sure how can you cast the
    entire array. If so, why not check for one of the elements in the list
    for its type using instanceof operator and then cast the entire array
    appropriately.
    I'm actually getting confused as to what exactly you are looking for.I should have been more clear on that point. Yes all elements will be of the same type, i.e., all of type ChildA or all of type ChildB.
    The problem comes in the fact that even though one has an Object[] array where all Objects are of type ChildA, a ClassCastException will still be thrown when casting to ChildA[]
    I have no idea what you're looking to do, but, regardless of what
    parent class you cast some instance as, the current implementation
    of each method is still going to execute. In other words, the
    toString method of some instance always returns the same String,
    whether you have it casted as a Parent or Child because it just
    returns the implemetnation of the current classTrue, except of course for methods that only exist on the child objects.
    A friend has given me a solution that I suspect will work:
    import java.lang.reflect.*;
    return (Parent[])list.toArray(Array.newInstance(parents[0].getClass(),0));

  • UISelectMany :  must be of type List or Array (ERROR with rich:pickLisT )

    Hi
    I have a problem with my <rich:pickList> I can't display the items. When executing the application I got the following error:
    java.lang.IllegalArgumentException: ValueBinding for UISelectMany :  must be of type List or Array
            at org.richfaces.utils.PickListUtils.findUISelectManyConverter(PickListUtils.java:59)
            at org.richfaces.utils.PickListUtils.findUISelectManyConverterFailsafe(PickListUtils.java:79)as the error message the selectItems is not a List but it is I can't understand.
    I transmit to you my backing bean
    @Stateful
    @Name("adminAction")
    @Scope(ScopeType.SESSION)
    public class AdminActionBean implements AdminActionLocal {
    @In(required=false)
       private List<String> customersChoice;
    @Out(required=false)
       private List<String> companyNames;
    @Factory("companyNames")
       public void selectCompanyNames(){
           setCompanyNames((List<String>) getEm().createQuery("select c.companyName from Customer c")
                        .getResultList());
    //getter() and settter...... my .xhtml page
    <rich:pickList id="customersChoice" value="#{customersChoice}">
                        <f:selectItems  id="companyNames" value="#{companyNames}" />
              </rich:pickList>Have you got any Idea. thanks for help
    regards
    bibou

    You might look up the SelectItem, as the value parameter for a f:selectItems must be a List<SelectItem>. Each SelectItem has both a value and a label.
    Or, you could use Tomahawk's t:selectItems which uses a more dataList-style attribute set to allow you to have the value be any List, and you can select items in the List's node to be the Label and the Value of the select option.
    Look em up, they're useful.

  • Need help on creating a linked list with array...

    I want to create a linked listed using array method. Any suggestion on how would I start it.
    thanks

    That means I want to implement linked list using an
    array.I believe you mean you want to implement list using an array. Linked list is a very different implementation of a list, which can be combined with arrays for a niche implementation of list, but I don't think this is what you're talking about.
    Do you mind if we ask why you don't want to use ArrayList? It does exactly what you specify, plus it will increase the size of the internal array as necessary to ensure it can store the required elements.
    If you really want to make your own, have a look at the source for ArrayList (in src.jar in your JDK installation folder) - it will answer any questions you have. If you don't understand any of the code, feel free to post the relevant code here and ask for clarification.

  • Put list in array

    Hi all,
    How to put list in array?? Is it true or not??
    What I mean is&#8230;I have list data like
    List 1 : 1 2 3 4
    List 2 : 2 3 4 5
    I want to put the list in array like
    [[1 2 3 4], [2 3 4 5]]
    Actually, can we do like this?
    Thank you very much.

    Hi jverd...
    Thank you very much....you help me a lot...I have another problem after settle the problem before...
    My problem is how to pass the list to another method??? I try to code but I get the object after I pass the list...My goals is want to compare line by line each other....
    Below is some of my code:      public static void hantarEquivalantClass(ArrayList s) {
              String[] s2 = (String[]) s.toArray(new String[0]);
              System.out.println("List Equivalance Class");
              System.out.println();
              for (int index = 0; index < s2.length; index++)
                        System.out.println(s2[index]);
              gunaStringTokenizer(s2);
             public static void gunaStringTokenizer(String[] s2) {
              List list = new LinkedList();
              for (int i = 0; i < s2.length; i++){
                   List list2 = new LinkedList();
                   StringTokenizer token = new StringTokenizer(s2, ",");
                   while (token.hasMoreTokens())
                        list2.add(token.nextToken());
                   list.add(list2);
              for (int i=0; i < list.size(); i++){
                   for (int j=0; j < list.size(); j++)
                        discernibility(list.get(i), list.get(j));
    //Here is problem....the object will pass not the list
    public static Set discernibility(List sRow, List sRowR) {
              Set s = new TreeSet();
              Iterator it = sRow.iterator();
                   while (it.hasNext()){
                        Object o = it.next();
                        if(!sRowR.contains( o ))
                        s.add( o );
              Iterator it2 = sRowR.iterator();
                   while (it2.hasNext()){
                        Object o2 = it2.next();
                        if(!sRow.contains( o2 ))
                        s.add( o2 );
              return s;

  • Need help with ouput of a list or array of numbers input from user

    I'm only a few weeks into learning java, so this may seem simple to some, but...
    I am trying to write a program that will receive numbers from a user,
    and then list, add, average those numbers. I've got the program to
    work except for listing the numbers that were input.
    Can someone help guide me????
    i've left the code I've tried in as comments.
    Enter an integer value, the program exits if the input is 0:
    20
    Enter an integer value, the program exits if the input is 0:
    40
    Enter an integer value, the program exits if the input is 0:
    60
    Enter an integer value, the program exits if the input is 0:
    80
    Enter an integer value, the program exits if the input is 0:
    0
    Total numbers entered: 4
    The array of numbers is: 0 0 0 0
    The sum is 200
    The average is 50
    The maximum number is 0
    The minimum is 0
    Here is my code:
    * Title:        Reads integers and finds the total, average, maximum of the input values
    * Description:
    * Copyright:    Copyright (c) 2002
    * Company:      Duke Court.
    * @author Mary Davenport
    * @version 1.0
    public class part3page6
      public static void main(String[] args)
      int data = 0;
      int sum = 0;
      int countnum = -1;
      int maximum = 0;
      int minimum = 0;
      int average = (countnum - 1);
      do
          System.out.println("Enter an integer value, " +
            " the program exits if the input is 0:  ");
          data = MyInput.readInt();
          sum += data;
          countnum++;
        } while (data != 0);
          //in order to figure the max & the min it appears that the
        //program will need to utilize arrays to store the individual numbers
        //that are input from the user.
        //create an array of the input data
        int[] number = new int[countnum];
        //creat a list of the input data
        int []myList = {data};
        //lists how many numbers entered
        System.out.println("Total numbers entered:  " + number.length);
        //list array of numbers -- this is giving me [I@3179c3,
        //instead of 20, 40, 60, 80 when I use "new int[countnum]"
    //     System.out.print("The array of numbers is: "
    //      + new int[countnum]);
        //list array of numbers:  this is giving me " 0 0 0 0 "
           //instead of 20, 40, 60, 80  with the following for statement
           // (number[i] + " ")
        System.out.print("The array of numbers is: ");
          for(int i=0; i<number.length; i++)
            System.out.print(number[i] + "  ");
      //list mylist of numbers from input, 20, 40, 60, 80
      //output is The list of numbers is: [I@3179c3
    //  System.out.print("The list of numbers is: " + myList);
        System.out.println();
        System.out.println("The sum is " +  sum);
        average = sum/countnum;
        System.out.println("The average is " + average);
        System.out.println("The maximum number is " +  maximum);
        System.out.println("The minimum is " +  minimum);

    When you input the data you need to save it to the array. Currently you are not saving the value you are just adding it
    ArrayList nums = new ArrayList();
       do
           System.out.println("Enter an integer value, " +
             " the program exits if the input is 0:  ");
           data = MyInput.readInt();
    nums.add(new Integer(data));
           sum += data;
           countnum++;
         } while (data != 0);

  • What is the proper and best way to destroy a java.util.List or Array for GC

    Hi,
    If I have a java.util.List of objects lets say:
    List<File> files = new ArrayList();The List contains 1000 file objects. When my class finishes, is it enough to do
    files = null;to make GC able to release it from memory?
    Cause it seems like I can't do the following:
    for(int i = 0; i < extracted_files.size(); i++){
                extracted_files.get(i) = null;
    }Or should I use this one:
    files.clear()What is the proper and best way to do this in order to avoid memory leaks? How about normal Arrays like File[]?
    Edited by: TolvanTolvanTolvan on 2009-sep-10 16:58

    TolvanTolvanTolvan wrote:
    Thanks for the info!
    But what if the List is a class variable running in a Web Service for like months without terminating?You mean if the List variable is a member variable of a long-lived object? Then presumably the list needs to live as long as the object does. In the unlikely scenario that the object needs to live on but its list member variable does not, then yes, setting the member to null will be needed to make the list eligible for GC. But I highly doubt this is your situation, and if it is, you probably have a design flaw.
    And if the list is referenced only by a local variable, then, as I already said, when the method ends, the variable goes out of scope, and the List is eligible for GC.
    Now, a slightly different situation is when the List needs to live a long time, and at some point during its life, you're done using some object that it refers to. In that situation, simply remove the element from the list (or set the element to null if it's an array rather than a list), and then if it's not referenced anywhere else, it can be GCed.
    How about Arrays like File[]? Do I need to iterate through the array and null all the objects or is it enough to just null the Array?YOU. DON'T. NEED. TO. HELP. GC. You don't need to set the elements to null, and you most likely don't even need to set the array variable to null.
    Also note that only references can be null, not objects.

  • Execute a procedure with a list of array in sql server 2008

    HI all,
    I have a procedure which has a list of values passed as an array . How can i execute my procedure with array list? how to implement this?Please help me.
    Thanks in advance
    Deepa

    Hi Deepa,
    basically Microsoft SQL Server does not support arrays as data types for procedures. What you can do is creating a type which represents a table definition. This type can than be used in a procedure as the following demo will show:
    The first script creates the environment which will be used for the execution
    -- 1. create the table as a type in the database
    CREATE TYPE OrderItems AS TABLE
    ItemId int PRIMARY KEY CLUSTERED
    GO
    -- 2. demo table for demonstration of results
    CREATE TABLE dbo.CustomerOrders
    Id int NOT NULL IDENTITY (1, 1) PRIMARY KEY CLUSTERED,
    CustomerId int NOT NULL,
    ItemId int
    GO
    -- 3. Insert a few records in demo table
    INSERT INTO dbo.CustomerOrders
    (CustomerId, ItemId)
    VALUES
    (1, 1),
    (2, 1),
    (3, 3),
    (1, 3);
    GO
    -- 4. Create the procedure which accepts the table variable
    CREATE PROC dbo.OrderedItemsList
    @Orders AS OrderItems READONLY
    AS
    SET NOCOUNT ON;
    SELECT o.*
    FROM dbo.CustomerOrders AS O INNER JOIN @Orders AS T_O
    ON (o.ItemId = T_O.ItemId);
    SET NOCOUNT OFF;
    GO
    The above script creates the table data type and a demo table with a few demo data. The procedure will accept the table data type as parameter. Keep in mind that table variable parameters have to be READONLY as parameter for procedures!
    The second script demonstrates the usage of the above scenario
    When the environment has been created the usage is a very simple one as you can see from the next script...
    -- 1. Fill the variable table with item ids
    DECLARE @o AS OrderItems;
    INSERT INTO @o (ItemId)
    VALUES
    (1), (3);
    -- 2. Get the list of customers who bought these items
    EXEC dbo.OrderedItemsList @Orders = @o;
    MCM - SQL Server 2008
    MCSE - SQL Server 2012
    db Berater GmbH
    SQL Server Blog (german only)

  • Linked Lists with Arrays

    I am setting up a linked list of the following very simplified class:
    class LinkedList
         String Name=" ";
         double ID=0;
         static long next=0;
    }the main class is as follows:
    class Links
         public static void Display(LinkedList Link)
         /** A Display function that simply displays everything within the LinkedList class*/
         System.out.println("\nName: " + Link.Name +"\nID  #: " + Link.ID + "\nNext ID: " + Link.next);
         public static void main(String[] args)
              int MAX_LINKS=10;
              LinkedList[] Link=new LinkedList[MAX_LINKS];
              for (int i=0;i<MAX_LINKS;i++)
                   Link.ID=i;
                   Link[i].next++;
                   Display(Link[i]);
    everything compiles fine, but at runtime I recieve a
    Exception in thread "main" java.lang.NullPointerException
    at Links.Display(Links.java:6)
    at Links.main(Links.java:18)What am I doing wrong?
    Thanks in advance.

    public static void main(String[] args){
       int MAX_LINKS=10;
    // this tells the compiler that the Link array will hold
    //LinkedList objects, but doesn't actually create those objects...
       LinkedList[] Link=new LinkedList[MAX_LINKS];
       for (int i=0;i<MAX_LINKS;i++){
    //NEED TO ADD THIS LINE to create the objects:
          Link[ i ] = new LinkedList();
          Link[ i ].ID=i;
          Link[ i ].next++;
          Display(Link[ i ]);

  • List to array question

    I have a list stored in mysql database that looks like this:
    12, 45, A, 87, B, 98
    I need to use coldfusion to retreive the list and convert
    each item to an element of an array. i.e.:
    tempArray [0] = 12;
    tempArray [1] = 45;
    and so on. I need to do this because I'm returning the
    created array to flash.
    Thanks for your help!

    If you literally want to return 12, 45, A, 87, B, 98, then
    understand that is not an array, it's a list. The example in your
    first post indicated you wanted an array - tempArray[1] = 12,
    tempArray[2] = 45, etc. Which is it, or am I confused?
    BTW, you don't need the [,] in the ListToArray function - I'm
    surprised it did not throw a compile error. Just do this: <cfset
    tempArray = ListToArray(detailsList)>

  • List to Array with Type

    Hi guys,
    I need to turn a List (an ArrayList specifically) into an array of Components.
    This is because I can't call a function like doSomething(Component ... components) with a collection. It needs to be an array correct?
    So, if it needs to be an array, I can't find a clean way to do it....or maybe I'm just a whiner.
    I can do this with
    theList.toArray(new Component[theList.size()]);or I can do it with
    (Component[])theList.toArray()But I don't like either of those...why should I have to pass an array in the first one and why should I be the one doing the cast in the second one?
    Shouldn't the ArrayList know how to return a correctly typed array?
    I wrote this little static method that I put in a helper class...does anything like this exist in the Collections class as a static method?
    I couldn't find anything like it in Arrays, or Collections etc.
    public static <T> T[] collectionToArray(Collection<T> l){
        Object ret[] = new Object[l.size()];
        int i = 0;
        for(T t : l){
            ret[i++] = t;
        return (T[]) ret;
    }If there is a better way to do this please let me know.
    Thanks,
    ~Eric

    ganeshmb wrote:
    It wasn't done because you either need an array of the proper type passed as a parameter, or a Class<T> passed as a parameter.Why? ArrayList is parametrized, which means it should be able to figure the data type by inspecting its contents, right? The only problem I see is, when its contents are empty, it will have to return null instead of an empty array. This is a different behavior from toArray, but should be acceptabe given the ease of use for clients - they don't have to pass an array instance to get the list back as an array.Wrong. In addition to the empty array behavior, suppose I have an List<Map>. I could have HashMap, ConcurrentHashMap, Properties, etc, all in this list. I still want a Map[] returned. What if my list is filled with HashMap? I still want a Map[] returned. Inspecting the contents is not a workable solution.

  • Comparing a string with a stored list(or array or ...)

    Hi all. I am trying to figure out the best way to do the following:
    I need to store serveral strings into a structure so that I can compare them against a string and see if the string is contained in the previously mentioned strings.
    I want to make the structure static, as it should not change, and I only need one instance of it, but I can't seem to come up with something I like. I was thinking of just using a string array and then running a loop comparing each position in the array to my string, but that seems inelegant to me for some reason. Anyone have any thoughts, or is that pretty much the best I am going to do ?
    thanks in advance.

    I might be inclined to use an ArrayList instead of an array of Strings, which would allow me to use use the contains method to do object comparisons so my code would end up looking more like this.
            ArrayList list = new ArrayList() ;
            list.add("Fred") ;
            list.add("Barney") ;
            list.add("Wilma") ;
            list.add("Betty") ;
            if(list.contains("Barney"))
                System.out.println("Hey Barney") ;
            else
                System.out.println("Absence of Barney detected") ;
            }But it's still doing the same thing you're describing under the hood.
    Hope this helps,
    PS.

  • Arrays of arrays or list of arrays?

    Hi!
    I've spent 2+ hours now trying to figure this out/browsing the web.
    I have x number of rows in db, and now I'm trying to convert this data to an array.
    Like this:
    String foo[] = null;
    Array unordered[];
    int i=0;       
    while(ResultSet.next()){
       foo = new String[]{  ResultSet.getString("osa_id"),
                            ResultSet.getString("k_teksti"),
                            ResultSet.getString("linkki"),
                            ResultSet.getString("taso"),
                            ResultSet.getString("k_alaisuus")};
       unordered[i] = valiaikainen;
       i++;
    }Compiles, but gives errors during run. In PHP this is annoyingly easy. (Grin.) Also I have to manipulate the order of the unordered, depending the data that arrays it contain holds. Is there easier way? Any help welcome, as I'm out of ideas.
    Thanks
    -9902468

    OOps. Stopid question.
    Figured it out right after posting the question...
    Well newbies are newbies, eh?
    -9902468

  • How to list an array of objects using struts in jsp and ActionForm

    I am using the struts ActionForm and need to know how to display an Array of objects. I am assuming it would look like this in the ActionForm:
    private AddRmvParts addRmv[];
    But I am not sure how the getter and setter in the ActionForm should look. Should it be a Collection or an Iterator?
    I am thinking I need to use an iterator in the jsp page to display it.
    I am also wondering if the AddRmvParts class I have can be the same class that gets populated by the retrieval of data from the database. This class has 10 fields that need to display on the jsp page in 1 row and then multiple rows of these 10 fields.
    Thanks.

    Most probably the easiest way to make it accessible in your page is as a collection.
    ie
    public Collection getAddRmvParts()
    You can use the <logic:iterate> or a <c:forEach>(JSTL) tag to loop through the collection
    As long as the individual items in the collection provide get/set methods you can access them with the dot syntax:
    Example using JSTL:
    <c:forEach var="addRmvPart" items="${addRmvParts}">
      <c:out value="${addRmvPart.id} ${addRmvPart.name} ${addRmvPart.description}"/>
    </c:forEach>

  • Printing on console list of arrays

    Iam asked to invoke a function which returns array of strings.how shall i print it on console..if u can suggest me any classes ,it wud be helpful.

    flounder wrote:
    meacod wrote:
    Unless they actually need to access it from another class. Then they need to know how to import and access, too :)Well g.pardhu lacks the ability to fully explain WTF they are trying to do.Very much agreed. Unfortunately they're not in as much of a minority here as I'd like, in that respect :(

Maybe you are looking for

  • Payroll in mid of month

    Hi All, Requirement : I need to run payroll for 5 employees in the mid of the month for Annual leave (unpaid), how i can run and post this without changing the payroll area , without affecting the other employees payroll Same scenario for Employee se

  • File sharing no longer works after upgrading from 10.3.9 to Leopard

    I'm trying to do file sharing on my PowerMac G5 with my MacBook Pro. The problem is when I try to connect to the G5 I get no response. Powermac G5 was just upgraded from 10.3.9 to Leopard 10.5.6 (clean install, then used Migration Assistant to copy o

  • Apps freeze when selecting a file

    Freezing is not quite correct but I experienced in a few apps (CB and BeBuzz) the following behaviour : When I select a file from the device / SD card (in CB to attach a pic or in BeBuzz to select a notification sound), the app get stuck in the file

  • Call BSP Application From ABAP

    Hi, I want to call BSP Application from ABAP. I've searched the forum and they all are displaying BSP Page in Container of the Screen. My requirement is to show it in a web browser. For that matter I am generating URL to call BSP Application. Followi

  • RAC environment setup for OEM Grid Control

    Hi All, One of my customer is setting up RAC environment for OEM Grid Control, he has following questions. 1) Can I use the DirectNFS client on each RAC node to mount SAN storage created with an OCFS2 filesystem? 2) Can I use the DirectNSF client to