Skip to content

Commit 404823e

Browse files
author
arbhard2
committed
Embedded Collections Project
1 parent f6bed66 commit 404823e

42 files changed

Lines changed: 2149 additions & 0 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

pom.xml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,12 @@
1414
<artifactId>junit</artifactId>
1515
<version>4.13.1</version>
1616
</dependency>
17+
<dependency>
18+
<groupId>org.hamcrest</groupId>
19+
<artifactId>hamcrest-library</artifactId>
20+
<version>1.3</version>
21+
<scope>test</scope>
22+
</dependency>
1723
</dependencies>
1824

1925
<build>
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
package com.ab.collection.advanced;
2+
3+
import java.util.Collections;
4+
import java.util.Iterator;
5+
import java.util.PriorityQueue;
6+
7+
/**
8+
* @author Arpit Bhardwaj
9+
*
10+
* PriorityQueue
11+
* implements Queue interface and provides a sorted element from the head of the queue
12+
* gurrantees the lowest or highest priority element will be on the head of the queue.
13+
* remove and poll fetch the priority element on head and next on priority will acquire the head spot via internal max/min heapification
14+
* default PriorityQueue is implemented with Min-Heap.
15+
*
16+
* Though it provides sorting, it's little different with other Sorted collections e.g. TreeSet or TreeMap,
17+
* which also allows you to iterate over all elements in sorted order,
18+
* instead in priority queue there is no guarantee of sorting on iteration.
19+
*/
20+
public class PriorityQueueDemo {
21+
public static void main(String[] args) {
22+
PriorityQueue<Integer> pq = new PriorityQueue<>(16);//default uses min heap
23+
//PriorityQueue<Integer> pq = new PriorityQueue<>(16, Collections.reverseOrder());// for max heap
24+
pq.add(3);
25+
pq.add(7);
26+
pq.add(2);
27+
pq.add(4);
28+
pq.add(1);
29+
pq.add(5);
30+
31+
printPriorityQueue(pq);
32+
33+
Integer head = pq.peek();
34+
35+
System.out.println("Size of Priority Queue : " + pq.size());
36+
System.out.println("Head of Priority Queue : " + head);
37+
38+
System.out.println("Polled Head of Priority Queue : " + pq.poll());
39+
40+
head = pq.peek();
41+
42+
System.out.println("Size of Priority Queue : " + pq.size());
43+
System.out.println("Head of Priority Queue : " + head);
44+
45+
printPriorityQueue(pq);
46+
}
47+
48+
private static void printPriorityQueue(PriorityQueue<Integer> pq) {
49+
Iterator<Integer> itr = pq.iterator();
50+
System.out.println("Printing Priority Queue..");
51+
while (itr.hasNext()){
52+
System.out.print(itr.next() + " ");
53+
}
54+
System.out.println();
55+
}
56+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package com.ab.collection.advanced;
2+
3+
import java.util.Date;
4+
import java.util.Map;
5+
import java.util.WeakHashMap;
6+
7+
/**
8+
* @author Arpit Bhardwaj
9+
*
10+
* WeakHashMap is an implementation of the Map interface that stores only weak references to its keys.
11+
* Storing only weak references allows a key-value pair to be garbage-collected when its key is no longer referenced outside of the WeakHashMap.
12+
*
13+
* It is useful for implementing "registry-like" data structures
14+
*/
15+
16+
17+
public class WeakHashMapDemo {
18+
public static void main(String[] args) throws InterruptedException {
19+
final Map<Person,PersonMetaData> weakMap = new WeakHashMap<>();
20+
Person p = new Person();
21+
weakMap.put(p,new PersonMetaData());
22+
23+
System.out.println(weakMap.toString());
24+
p = null;
25+
System.gc();
26+
Thread.sleep(1000);
27+
System.out.println(weakMap.toString());
28+
}
29+
}
30+
31+
final class Person{
32+
33+
}
34+
35+
class PersonMetaData{
36+
Date date;
37+
38+
public PersonMetaData() {
39+
date = new Date();
40+
}
41+
42+
@Override
43+
public String toString() {
44+
return "PersonMetaData{" +
45+
"date=" + date +
46+
'}';
47+
}
48+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.ab.collection.arrays;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* @author Arpit Bhardwaj
7+
*
8+
*/
9+
public class ArrayDemo {
10+
public static void main(String[] args) {
11+
//initialization
12+
int[] ids = new int[10];
13+
//int[] ids = new int[]{1,2,3,4,5};
14+
//int[] ids = {1,2,3,4,5}; //anonymous array
15+
16+
//you can type the [] before or after the name, and adding a space is optional.
17+
//int []ids = new int[10];
18+
//int [] ids = new int[10];
19+
//int ids[] = new int[10];
20+
//int ids [] = new int[10];
21+
22+
//int[] ids; //not valid as down in when we use it and compiler will complain
23+
//int[] ids = new int[0]; //valid create an array of length 0
24+
int[] ids1; //valid as we are not using this in the code
25+
int[] ids2,ids3;
26+
27+
//Accessing and Iteration
28+
for (int i = 0; i < ids.length; i++) {
29+
ids[i] = i+1;
30+
System.out.print(ids[i]);
31+
}
32+
33+
System.out.println();
34+
35+
for (int id: ids) {
36+
System.out.print(id);
37+
}
38+
39+
System.out.println();
40+
}
41+
}
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
package com.ab.collection.arrays;
2+
3+
import java.util.Arrays;
4+
5+
/**
6+
* @author Arpit Bhardwaj
7+
*
8+
* Method When arrays are the same When arrays are different
9+
* Arrays.equals() true false
10+
* Arrays.compare() 0 positive or negative number
11+
* Arrays.mismatch() -1 Zero or positive index
12+
*/
13+
14+
public class ArraysClassDemo {
15+
public static void main(String[] args) {
16+
String[] instruments = new String[]{"Guitar","drums","bass"};
17+
18+
/******** sort ********/
19+
Arrays.sort(instruments);
20+
System.out.println(Arrays.toString(instruments));
21+
22+
int[] fib = new int[]{0,1,5,2,3,1,8,13};
23+
Arrays.sort(fib); //uses Dual-Pivot Quicksort algorithm
24+
System.out.println(Arrays.toString(fib));
25+
//Arrays.parallelSort(fib); //uses parallel merge sort
26+
27+
/******** search ********/
28+
//Array should be sorted else it returns un deterministic result.
29+
//returns index of the search key, if it is contained in the array; otherwise, (-(insertion point) - 1).
30+
//if element is greater than all elements in array then -arr.length-1
31+
//if element is smaller than all elements in array then -0-1 = -1
32+
System.out.println(Arrays.binarySearch(fib,4)); //(-5-1) = -6
33+
34+
/******** comparison ********/
35+
int[] arr1 = new int[]{1,2,3};
36+
int[] arr2 = new int[]{1,2,3};
37+
System.out.println(arr1.equals(arr2)); //false
38+
System.out.println(arr1 == arr2); //false
39+
System.out.println(Arrays.equals(arr1,arr2)); //true
40+
41+
//smaller,equal,bigger comparison (Java 11 Addition)
42+
//compare do lexicographically comparison of array
43+
//0 if equal,-1 if arr1 is smaller, +1 if arr1 is larger
44+
//If both arrays are the same length and have the same values in each spot in the same order, return zero.
45+
//If all the elements are the same but the second array has extra elements at the end, return a negative number.
46+
//If all the elements are the same but the first array has extra elements at the end, return a positive number.
47+
//If the first element that differs is smaller in the first array, return a negative number.
48+
//If the first element that differs is larger in the first array, return a positive number.
49+
System.out.println(Arrays.compare(new int[]{1,2}, new int[]{1})); //1
50+
System.out.println(Arrays.compare(new int[]{1,2}, new int[]{1,2})); //0
51+
System.out.println(Arrays.compare(new int[]{1,2}, new int[]{1,2,3})); //-1
52+
System.out.println(Arrays.compare(new int[]{2,3}, new int[]{1,3})); //1
53+
System.out.println(Arrays.compare(new int[]{1,2}, new int[]{2,3})); //-1
54+
55+
//null < numbers < uppercase letters < lowercase letters
56+
System.out.println(Arrays.compare(new String[]{"abcd"}, new String[]{"ABCD"})); //32
57+
58+
//mismatch() returns the index of the first element that is different.-1 if the arrays are equal
59+
System.out.println(Arrays.mismatch(new int[]{1,2}, new int[]{1,2,4})); //2
60+
61+
/******** copying ********/
62+
//Method 1
63+
/*System.arraycopy(<source array>,
64+
<source position>,
65+
<destination array>,
66+
<destination position>
67+
<length of content to copy from source>);*/
68+
69+
70+
//Method 2
71+
/*Arrays.copyOf(<source array>,
72+
<new array length>);*/
73+
74+
//Method 3
75+
/*Arrays.copyOfRange(<source array>,
76+
<start position>,
77+
<end position>);*/
78+
79+
//all below declaration are valid
80+
//int[][] multi = new int[2][2];
81+
//int multi[][] = new int[2][2];
82+
//int[] [] multi = new int[2][2];
83+
//int[][] multi = new int[2] [2];
84+
//int[] multi [] = new int[2][2];
85+
//int[] multi2d [], multi3d [][]; // a 2D AND a 3D array
86+
87+
//asymmetric multidimensional array
88+
int [][] asymulti = new int[4][];
89+
asymulti[0] = new int[5];
90+
asymulti[1] = new int[3];
91+
}
92+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.ab.collection.arrays;
2+
3+
import java.util.Arrays;
4+
/**
5+
* @author Arpit Bhardwaj
6+
*
7+
* In methods accepting varargs parameter, you can pass arrays or directly comma separated elements
8+
*/
9+
public class Varargs {
10+
//valid
11+
/*public static void main(String[] args) {
12+
System.out.println(Arrays.toString(args));
13+
}*/
14+
15+
//valid
16+
/*public static void main(String args[]) {
17+
System.out.println(Arrays.toString(args));
18+
}*/
19+
//valid
20+
public static void main(String... args) {
21+
System.out.println(args.length);
22+
//System.out.println(args[0]);//throws ArrayIndexOutOfBoundsException for invalid index
23+
args = new String[10];
24+
System.out.println(args.length);
25+
26+
27+
walk(1); // 0
28+
walk(1, 2); // 1
29+
walk(1, 2, 3); // 2
30+
walk(1, new int[] {4, 5}); // 2
31+
walk(1,null); // throws NullPointerException in walk
32+
33+
//varargs can only be used as a method parameter.
34+
//String... s = ""; //compile error
35+
}
36+
37+
public static void walk(int start, int... nums) {
38+
System.out.println(nums.length);
39+
}
40+
41+
}
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package com.ab.collection.basic;
2+
3+
import com.ab.collection.model.Product;
4+
5+
import java.util.*;
6+
7+
/**
8+
* @author Arpit Bhardwaj
9+
*
10+
* The right side of the for-each loop must be one of the following:
11+
* A built-in Java array
12+
* An object whose type implements java.lang.Iterable
13+
*
14+
* Hence, Map is not supported in a for-each loop
15+
*/
16+
public class CollectionDemo {
17+
public static void main(String[] args) {
18+
Product door = new Product("Door", 35);
19+
Product floorPanel = new Product("Panel", 25);
20+
Product window = new Product("Window", 10);
21+
22+
Collection<Product> products = new ArrayList<>();
23+
products.add(door);
24+
products.add(floorPanel);
25+
products.add(window);
26+
27+
//System.out.println(products);
28+
29+
//by iterator
30+
final Iterator<Product> productIterator = products.iterator();
31+
while (productIterator.hasNext()){
32+
Product product = productIterator.next();
33+
System.out.println(product);
34+
}
35+
36+
//by for each loop
37+
for (Product product:products) {
38+
System.out.println(product);
39+
}
40+
41+
//remove element while iterating can only be done using iterator
42+
final Iterator<Product> productIterator2 = products.iterator();
43+
while (productIterator2.hasNext()){
44+
Product product = productIterator2.next();
45+
if(product.getWeight() > 20){
46+
System.out.println(product);
47+
}
48+
else{
49+
productIterator2.remove();
50+
//products.remove(product); //throw ConcurrentModificationException
51+
}
52+
}
53+
54+
// for-each loop implicitly creates an iterator, but it is not exposed to the user.
55+
// so if you use a collection modifying methods then it throws ConcurrentModificationException
56+
try{
57+
for (Product product:products) {
58+
if(product.getWeight() > 30){
59+
System.out.println(product);
60+
}
61+
else{
62+
//products.remove(product); //throw ConcurrentModificationException
63+
//products.clear(); //throw ConcurrentModificationException
64+
//products.add(window); //throw ConcurrentModificationException
65+
}
66+
}
67+
}catch (Exception e){
68+
e.printStackTrace();
69+
}
70+
71+
System.out.println(products.size()); //2
72+
System.out.println(products.isEmpty()); //false
73+
System.out.println(products.contains(door)); //true
74+
System.out.println(products.contains(window)); //false
75+
76+
Collection<Product> otherProducts = new ArrayList<>();
77+
otherProducts.add(window);
78+
otherProducts.add(door);
79+
80+
System.out.println(products.containsAll(otherProducts)); //false
81+
products.removeAll(otherProducts);
82+
System.out.println(products);
83+
}
84+
}

0 commit comments

Comments
 (0)