การใช้งาน Array ใน jsp
หน้าแรก JSP การใช้งาน Array ใน jsp
Array is used to store similar type of data in series. E.g. fruits name
Fruits can be a mango, banana, and apple. Name of students in classroom
denote to 10th Standard, Bachelor in science can have group of 30 to
40 students.
Arrays can be String array, int array, and dynamic arrays are ArrayList, vector
We will look String array in this JSP
| simpleArray.jsp | Output |
<%@ page contentType="text/html; charset=iso-8859-1" language="java" %> <% String[] stArray={"bob","riche","jacky","rosy"}; %> <html> <body> <% int i=0; for(i=0;i<stArray.length;i++) { out.print("stArray Elements :"+stArray[i]+"<br/>"); } %> </body> </html>
This String Array has four elements. When we go through this array, have to use loop either for or while loop. We are using here for loop, First stArray.length give use total number of elements in array then we fetch one by one for loop iterator. Array starts from zero so here we have only 0,1,2,3 elements if we try to get stArray[4] it will throw
java.lang.ArrayIndexOutOfBoundsException: 4.
| stringArray.jsp | Output |
<%@ page contentType="text/html; charset=iso-8859-1" language="java" %> <% String[] stArray=new String[4]; stArray[0]="bob"; stArray[1]="riche"; stArray[2]="jacky"; stArray[3]="rosy"; %> <html> <body> <% int i=0; for(i=0;i<stArray.length;i++) { out.print("stArray Elements :"+stArray[i]+"<br/>"); } %> </body> </html>
Integer Array in JSP
| intArray.jsp | Output |
<%@ page contentType="text/html; charset=iso-8859-1" language="java" %> <% int[] intArray={23,45,13,54,78}; %> <html> <body> <% int i=0; for(i=0;i<intArray.length;i++) { out.print("intArray Elements :"+intArray[i]+"<br/>"); } %> </body> </html>
Dynamic arrays are automatically growable and reduceable according to per requirement. We dont need to define it size when declaring array. It takes extra ratio of capacity inside memory and keeps 20% extra.
Vector
ArrayList
| vectorArray.jsp | Output |
<%@ page import="java.util.Vector" language="java" %> <% Vector vc=new Vector(); vc.add("bob"); vc.add("riche"); vc.add("jacky"); vc.add("rosy"); %> <html> <body> <% int i=0; for(i=0;i<vc.size();i++) { out.print("Vector Elements :"+vc.get(i)+"<br/>"); } %> </body> </html>
ArrayList
ArrayList also same just it is unsynchronized, unordered and faster than vector.
| ArrayList.jsp | Output |
<%@ page import="java.util.ArrayList" language="java" %> <% ArrayList ar=new ArrayList(); ar.add("bob"); ar.add("riche"); ar.add("jacky"); ar.add("rosy"); %> <html> <body> <% int i=0; for(i=0;i<ar.size();i++) { out.print("ArrayList Elements :"+ar.get(i)+"<br/>"); } %> </body> </html>
ขึ้นไปด้านบน
