Java ArrayList - 1
Why Array List is better than Array :
Array has fix length but Array List can dynamically grow and shrink after insert or delete operation.
Also Array List can use predefined methods which makes our task easy, for example if you want to delete an element from the array list all you have to do is " arraylist.remove(element name) ".
Create an Array List :
-Default Format
ArrayList<"type"> "name_of_the_arrayList" = new ArrayList<>();
-Create An Integer type Array List
ArrayList<Integer> arrInt = new ArrayList<>();
-Create An String type Array List
ArrayList<String> arrString = new ArrayList<>();
Add elements to an Array List :
-Add Integer element to arrInt
arrInt.add(1);
-Add String element to arrString
arrString.add("hello");
-Add an element at the specified location in ArrayList :
arrString.add(1,"world"); //This will add "world" at the 1st position
Remove elements from an Array List :
-Remove element by key
arrString.remove("world"); //Removing "world" from arrString
**If there is more than one element named "world" it will only remove the first one
to remove all of them use
arrString.removeAll(Arrays.asList("world"));
-Remove element by index
arrInt.remove(0); //Remove 1st element from arrInt
Lets write the complete code:
To use Array List import java.util.ArrayList;
CHECK NEXT TUTORIAL ON ARRAY LIST
Java Array List - 2
Comments
Post a Comment