In Java, a Collection is an interface that defines a group of objects as a single unit. It provides a way to manage a group of objects efficiently and conveniently, and is a fundamental part of the Java Collections Framework.
The Java Collections Framework provides a set of interfaces and classes that implement various types of collections, such as lists, sets, maps, and queues. These collections can be used to store and manipulate objects in various ways, depending on the specific needs of the application.
Here’s an example of how to create and use a simple ArrayList, which is an implementation of the List interface in the Java Collections Framework:
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
// create a new ArrayList
ArrayList<String> myArrayList = new ArrayList<>();
// add some elements to the ArrayList
myArrayList.add("apple");
myArrayList.add("banana");
myArrayList.add("orange");
// print out the contents of the ArrayList
for (String s : myArrayList) {
System.out.println(s);
}
}
}
In this example, we first import the ArrayList class from the java.util package. We then create a new ArrayList called "myArrayList" and add some strings to it using the "add" method. Finally, we loop through the contents of the ArrayList using a "for each" loop and print out each element.
Here’s an example of how to use some common methods of the ArrayList class:
import java.util.ArrayList;
public class Example {
public static void main(String[] args) {
// create a new ArrayList
ArrayList<Integer> myArrayList = new ArrayList<>();
// add some elements to the ArrayList
myArrayList.add(5);
myArrayList.add(10);
myArrayList.add(15);
// get the size of the ArrayList
int size = myArrayList.size();
System.out.println("Size of ArrayList: " + size);
// get an element from the ArrayList
int element = myArrayList.get(1);
System.out.println("Element at index 1: " + element);
// remove an element from the ArrayList
myArrayList.remove(2);
// print out the contents of the ArrayList
for (int i = 0; i < myArrayList.size(); i++) {
System.out.println(myArrayList.get(i));
}
}
}
In this example, we create an ArrayList of integers and add some elements to it using the "add" method. We then use the "size" method to get the size of the ArrayList, the "get" method to get an element at a specific index, and the "remove" method to remove an element at a specific index. Finally, we loop through the contents of the ArrayList using a "for" loop and print out each element.