Java Collection is a framework that provides an architecture for storing and manipulating a group of objects. It is a built-in library that provides many interfaces for collection types and implementations for every interface. The package library for Java Collection is java.util.
Example 1: ArrayList An ArrayList is an ordered collection that can store multiple elements of the same type. It is implemented using an array internally, hence its name. To use an ArrayList, you need to import the java.util package. Here's an example of how it could be used:
import java.util.ArrayList;
public class Example { public static void main(String[] args) { // Create an ArrayList of Integers ArrayList numbers = new ArrayList();
// Add some elements to the ArrayList numbers.add(1); numbers.add(2); numbers.add(3);
Example 2: HashSet A HashSet is an unordered collection that does not allow duplicates. It uses a hash table internally to store the elements. You need to import the java.util package to use it. Here's an example of how it could be used:
import java.util.HashSet;
public class Example { public static void main(String[] args) { // Create a HashSet of Strings HashSet cars = new HashSet();
// Add some elements to the HashSet cars.add("Toyota"); cars.add("Honda"); cars.add("Nissan");
Example 3: HashMap A HashMap is a key-value pair collection that stores values based on their hash codes. It is implemented using a hash table algorithm. You need to import the java.util package to use it. Here's an example of how it could be used:
import java.util.HashMap;
public class Example { public static void main(String[] args) { // Create a HashMap of Strings HashMap months = new HashMap();
// Add some elements to the HashMap months.put(1, "January"); months.put(2, "February"); months.put(3, "March");
// Get a value from the HashMap System.out.println(months.get(1)); // Output: January } }
In conclusion, the Java Collection framework library provides interfaces and implementations of various collection types. It's a built-in library in Java and can be imported using the java.util package. Example collections include ArrayList, HashSet, and HashMap.
Java Collection - 30 examples found. These are the top rated real world Java examples of Collection from package DSAAJ2-Answers extracted from open source projects. You can rate examples to help us improve the quality of examples.