• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 257
  • Last Modified:

What is the best Class to use to add an "array" into an "array"?

Hi,

I dunno how to explain my problem cos it's quite complicated. This is my JSP code,

<%@ page language="java" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="org.apache.commons.dbutils.DbUtils" %>
<%@ page import="com.dm.sms.config.DbConfig" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.LinkedList" %>
<%@ page import="java.io.PrintWriter" %>

<HTML>

<%
            List menu = null;
            PrintWriter outHtml = response.getWriter();
            
            out.println("Content-Type: text/javascript");
            menu = getNodes();
            printTree("TREE_NODES", menu, outHtml);
%>

<%!

public List getSubNodes(int parent) {
            
            int nodeId = 0;
            String caption = "";
            String url = "";
            String targetFrame = "";
            List list = null;
            List node = null;
            List subNodes = null;
            String sqlStr = "";
            Connection conn = null;
            PreparedStatement statement = null;
            ResultSet rs = null;

            try {
                  DbUtils.loadDriver(DbConfig.dbDriver);
                  conn = DriverManager.getConnection(DbConfig.dbUrl);

                  sqlStr = "SELECT NodeID, Caption, Url, Target FROM treemenu WHERE ParentID=" + parent;

                  statement = conn.prepareStatement(sqlStr);
                  rs = statement.executeQuery();
                  
                  list = new LinkedList();
                  node = new LinkedList();
                  subNodes = new LinkedList();
                  
                  while (rs.next()) {
                        nodeId = rs.getInt(1);
                        caption = rs.getString(2);
                        url = rs.getString(3);
                        targetFrame = rs.getString(4);
                        
                        node.add(new Integer(nodeId));
                        node.add(caption);
                        node.add(url);
                        node.add(targetFrame);
                        
                        //DEBUG
                        System.out.println("---------------------------");
                        System.out.println("nodeId=" + nodeId);
                        System.out.println("caption=" + caption);
                        System.out.println("url=" + url);
                        System.out.println("targetFrame=" + targetFrame);
                        System.out.println("NODE=" + node.toString());
                        System.out.println("---------------------------");
                        System.out.println("\n");
                        
                        subNodes = getSubNodes(nodeId);
                        
                        if (subNodes != null) {
                              node.add(subNodes.toString());
                              list.add(node.toString());
                        }
                  }
            } catch (SQLException e) {
                  e.printStackTrace();
            } finally {
                  DbUtils.closeQuietly(rs);
                  DbUtils.closeQuietly(statement);
                  DbUtils.closeQuietly(conn);
            }
            
            return list;
      }
%>

<%!
      public List getNodes() {
            return getSubNodes(0);
      }
%>

<%!
      public String q(String value) {
            return !value.equals("") ? "'" + value + "'" : "null";
      }
%>

<%!
      public void printNodes(List nodes, PrintWriter out) {
            
            List subList = null;
            
            for (int i = 0; i < nodes.size(); i++) {
            
            //DEBUG
            //System.out.println("nodes=" + nodes.toString());
            System.out.println("**********************************");

                  //out.println("[" + q(nodes.get(i).toString()) + ", " +  q(nodes.get(i+1).toString()) + ", " + q(nodes.get(i+2).toString()));
                  out.println(q(nodes.get(i).toString()) + ", " +  q(nodes.get(i+1).toString()) + ", " + q(nodes.get(i+2).toString()));
                  
                  if (!nodes.get(i+3).equals("")) {
                        
                        out.println(",\n");
                        subList = nodes.subList(i+3, nodes.size());
                        printNodes(subList, out);
                        
                  }
                   out.println("]");
                  
                  if (i < (nodes.size() - 1)) {
                         out.println(",");
                         out.println("\n");
                  }
            }
      }
%>

<%!
      public void printTree(String treeName, List nodes, PrintWriter out) {
            out.println("var " + treeName + " = [\n");
            printNodes(nodes, out);
            out.println("];\n");
      }
%>
      
</HTML>

My problem is that in getSubNodes method, i need to recursively add the data from the db table to the List. I'm not sure if List is the right class to use. Because, when i recursively add the data, it also adds the squared braces ("[ ]"). I do not want any braces in my array.

So do anyone knows any Java class that,

-has a add method
-can add itself into another same class
-has a get method w/o requiring index/keys
-maybe a subList method.

Any help is apppreciated.

Melv.
0
mwhc
Asked:
mwhc
  • 4
  • 2
1 Solution
 
bloodredsunCommented:
How about an ArrayList?

-has a add method --> Yes
-can add itself into another same class --> Yes. You can add any object
-has a get method w/o requiring index/keys -->Yes. Same as List
-maybe a subList method.  -->Yes. Inheirits subList from List.
0
 
bloodredsunCommented:
Also has the very useful method toArray() which returns the ArrayList as an Object array which you can then cast to your object type.
0
 
mwhcAuthor Commented:
Ok, then how do i get rid of the squared braces? Will it add the square braces everytime i to a .toArray()? or add itself into another ArrayList?
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
mwhcAuthor Commented:
Ok, FYI i wish to produce a javascript from the JSP. It's something like this.

From DB table.

create table treemenu (
      NodeID int primary key not null,
      ParentID int,
      Caption char(100),
      Url char(255),
      Target char(50),
      Disabled char(1)
);
insert into treemenu values ( 10, 0, 'Home', 'http://javascript.cooldev.com/', '', 'N');
insert into treemenu values ( 20, 10, 'Scripts', '', '', 'N');
insert into treemenu values ( 30, 20, 'COOLjsTree', '', '', 'N');
insert into treemenu values ( 40, 20, 'COOLjsTree PRO', '', '', 'N');
insert into treemenu values ( 50, 20, 'COOLjsMenu', '', '', 'N');
insert into treemenu values ( 60, 0, 'Download', '', '', 'N');
insert into treemenu values ( 70, 60, 'Pricing', '', '', 'N');
insert into treemenu values ( 80, 0, 'Contacts', '', '', 'N');
insert into treemenu values ( 90, 80, 'Sales', '', '', 'N');
insert into treemenu values ( 100, 80, 'Support', '', '', 'N');


To Javascript (below is an example),

var TREE_NODES = [
  ['NORTH', 'north.htm', null,
    ['PERAK', 'perak.htm', null,
      ['IPOH', 'ipoh.htm', null,
        ['SS1-A', '../ss1a.jsp?id=test', null]],
      ['TAIPING', 'taiping.htm', null,
        ['SS2-A', 'ss2a.htm', null]],
      ['SITIAWAN', 'sitiawan.htm', null,
        ['SS3-A', 'ss3a.htm', null]]]],
  ['SOUTH', null, null,
    ['JOHOR', null, null,
      ['JOHOR BAHRU', 'jb.htm', null,
        ['SS1-A', 'ss1a.htm', null]],
      ['PASIR GUDANG', null, null,
        ['SS2-A', 'ss2a.htm', null]],
      ['KLUANG', null, null]]],
  ['EAST', 'east.htm', null,
    ['KELANTAN', null, null,
      ['KOTA BAHRU', null, null]]],
  ['CENTRAL', 'central.htm', null,
    ['KUALA LUMPUR', 'kl.htm', null,
      ['CHERAS', null, null],
      ['SETAPAK', null, null],
      ['SELAYANG', null, null]]]
];


Melv.

0
 
bloodredsunCommented:
>>Will it add the square braces everytime i to a .toArray()? or add itself into another ArrayList?
Only if you call toString() on it, which is the wrong thing to do. You need to iterate over the object to output the values not just call toString().

Here's some Proof Of Concept code
ArrayList.jsp
-------------
<%@ page import="java.util.*" %>

<html>
<head><title>ArrayList Example</title></head>
<body>
<%
ArrayList arrList = new ArrayList() ;

ArrayList arrList1 = new ArrayList() ;
arrList1.add( "1" ) ;
arrList1.add( "2" ) ;
arrList1.add( "3" ) ;
arrList1.add( "4" ) ;

ArrayList arrList2 = new ArrayList() ;
arrList2.add( "Bert" ) ;
arrList2.add( "Ernie" ) ;
arrList2.add( "Bob" ) ;
arrList2.add( "Jeff" ) ;

ArrayList arrList3 = new ArrayList() ;
arrList3.add( "Dog" ) ;
arrList3.add( "Cat" ) ;
arrList3.add( "Mouse" ) ;
arrList3.add( "Elk" ) ;

//add all to the container ArrayList
arrList.add( arrList1 ) ;
arrList.add( arrList2 ) ;
arrList.add( arrList3 ) ;


//Iterate over the main ArrayList
for (Iterator it = arrList.iterator (); it.hasNext (); ) {
      ArrayList subArrayList = (ArrayList) it.next ();
            //Iterate over the sub ArrayLists
            for (Iterator subIt = subArrayList.iterator (); subIt.hasNext (); ) {
                  out.println( subIt.next ()+ "<br>") ;
            }
}

%>
</body>
</html>
---------------

See, no square brackets and you can put ArrayLists into an ArrayList and also iterate over them with no index required.

As an aside, your JavaScript code would be much improved by using JavaScript Object arrays as it would be much cleaner.
0
 
bloodredsunCommented:
agreed
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 4
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now