ArrayList in Java Flashcards
what is an ArrayLists?
An ArrayLists is a resizable Array.
How do you create an ArrayLists?
- ArryList<Integer> integers;
// null
integers = new ArrayList<>();
// the the object in the
memory
2.</Integer>
How do you add element to an array list?
- you can add element to an array list by using the Add(); method.
a. fruits.add(“apple”);
fruits.add(“Bananna);
b.add(index , element)
fruits.add(0 , apple);
How do you access element in an ArrayLists?
- you can access an element using the get(); method
a.fruit.get(0);
// get the first element in the ArrayList
How do you change element in an ArrayList?
- we can change the element in the arrayList by using the set method.
a. set(index, element)
fruit.set(0, orange);
// change the first element
to orange in the array list.
How do you remove an element in an ArrayList?
To remove an element use the remove(); method
a.to remove by index:
fruit.remove(0);
// remove the first element in
the arraylist.
b. to remove by value:
fruit. remove(“apple”);
// remove the value apple from the arrayList
c. to remove all element use the clear(); method
fruit.clear();
How do we get the Size of an ArrayList?
To get the size of An ArrayList use the size(); method
a. fruit.size();
// get the size of the arraylist.
How to loop through an array list?
You can use a for loop to loop through an arraylist.
example:
for(int i = 0; i < fruit.size(); i++)
System.out.print(fruit.get(i));
// this loop and get the element in the array list using the size(); method
How do you sort An ArrayList?
To sort An array list you use the sort(); method from the collection class then pass the name of the arraylist to the sort(); method
what is the for each loop?
the for each loop is use for iterating over array and arraylists.
how to declare a for each loop
for( Type - varname : Arraylists/array)
example: itemArraylist.add(“orange);
for(String item : itemArrayList)
system.out.print(item + “ “
Why do we use array?