ArrayList
- Values could be duplicated
- Use to store multiple "elements" together, represented by single variable name
- The "elements" could be of different Data types such as int, double, Objects
- No need to specify size while declaration, size = Dynamic
- Element can be accessed using array "index"
- Array index starts from zero [0]
--------------------------------------------------------------------------------------
Ex. 1: ArrayList
Source: TestArrayList.java
import java.util.ArrayList;- No need to specify size while declaration, size = Dynamic
- Element can be accessed using array "index"
- Array index starts from zero [0]
--------------------------------------------------------------------------------------
Ex. 1: ArrayList
Source: TestArrayList.java
public class TestArrayList {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("Tokyo");
list.add("Edogawa ku");
list.add("Minato ku");
list.add("Toshima ku");
Customer cust = new Customer();
list.add(cust); // object can be added to ArrayList
System.out.println(list.get(3));
}
}
Output:
======================================================
HashMap
- Use to store data in key and value pair
- Key should be unique and of reference data type
- No need to specify size while declaration, size = Dynamic
---------------------------------------------------------------------------------------
Ex. 2: HashMap
Source: TestHashMap.java
public class TestHashMap {
public static void main(String[] args) {
HashMap hash = new HashMap();
//key and value pair (phone/name)
hash.put("5678", "Yamada");
hash.put("8934", "Suzuki");
hash.put("1234", "John");
System.out.println(hash.get("8934"));
}
}
Output:
======================================================
TreeSet
- Use to store unique values, no duplicates
- Use to store multiple "elements" together, represented by single variable name
- The "elements" could be of different Data types such as int, double, Objects
- No need to specify size while declaration, size = Dynamic
- Element can be accessed using array "index"
- Array index starts from zero [0]
----------------------------------------------------------------------------------------- Element can be accessed using array "index"
- Array index starts from zero [0]
Ex. 3: TreeSet
Source: TestTreeSet.java
import java.util.TreeSet;
public class TestTreeSet {
public static void main(String[] args) {
public class TestTreeSet {
public static void main(String[] args) {
tset.add(1);
tset.add(2);
tset.add(3);
tset.add(3);
System.out.println(tset.toString());
}
Output:
tset.add(2);
tset.add(3);
tset.add(3);
System.out.println(tset.toString());
}
}
Output:
[1,2,3]