In JAVA when you define an array you must know in advance how much elements there would be, once defined you cannot grow or shrink that array. There comes a problem when you do not know the exact amount of data that would come, more data mean more space required to handle this situation we have to dynamically increase the size of the array or use some other way to handle this situation.
In this tutorial we will see Two different ways to solve the said issue.
In this tutorial we will see Two different ways to solve the said issue.
- Using Vector
- Using ArrayList
Vectors
Vector is special type of array that expands dynamically as objects are added to itprivate void IncreaseArrayLengthUsingVector(){ Vector v=new Vector(); System.out.println("Vector Size = "+v.size()); // Adding items to Vector v.add("Item 1"); v.add("Item 2"); v.add("Item 3"); v.add("Item 4"); System.out.println("Vector Size = "+v.size()); // Vector indexs are zero based System.out.println("Item At Index 2 = "+v.get(1)); // Removing an Item v.remove(2); System.out.println("Vector Size = "+v.size()); // Printing All Elements in Vector System.out.println("All elements in Vector = "+v); }
Array List
You can also use ArrayList which extends AbstractList class and Implements List interface, usage is almost similar as that of Vector.private void increaseArrayLengthUsingArrayList(){ ArrayList al = new ArrayList(); System.out.println("ArrayList Size = " + al.size()); // Adding items to the ArrayList al.add("JAVA"); al.add("PHP"); al.add("C#"); al.add("HTML"); al.add("Javascript"); al.add("CSS"); System.out.println("ArrayList Size = " +al.size()); // Remove item from the ArrayList al.remove(2); System.out.println("ArrayList Size = " + al.size()); // Display the ArrayList System.out.println("All elements in ArrayList" + al); }
0 comments:
Post a Comment