Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Java Collection and Generics
- ## Arrays
- Define a fixed length **Array**
- int a[] = new int[4];
- If you know the exact size, go for array. It's faster
- ## Collection
- * Size is not fixed
- * Items can have duplicate values
- * The type here will be int Object type. You can add string, integer, etc...
- * Doesn't have index, use **List** instead of Collection if you need indexing.
- * You can traverse elements in sequence
- *Class Hierarchy:* Collection (Interface) -> List (Interface) -> ArrayList (Class)
- Collection values = new ArrayList();
- values.add(5);
- values.add(6);
- Use **Generics** to restrict types on a collection
- \<Integer> is a sample Generic, it can be string, integer or custom object.
- Collection<Integer> values = new ArrayList<>();
- ## Set
- * Can only have unique values
- * **HashSet** return elements in random order
- Sample HashSet
- Set<Integer> numbers = new HashSet<>();
- A **TreeSet** returns the element in sorted order.
- ## Map
- * Map have key value pair
- * Map is an interface
- Sample HashMap
- Map<Integer, String> m = new HashMap<>();
- <!--stackedit_data:
- eyJoaXN0b3J5IjpbLTEwMDU3ODE3MjBdfQ==
- -->
Add Comment
Please, Sign In to add comment