File tree 1 file changed +56
-0
lines changed
src/main/java/com/sorting/demonstration/arrays
1 file changed +56
-0
lines changed Original file line number Diff line number Diff line change
1
+ package com .sorting .demonstration .arrays ;
2
+
3
+ import java .util .HashMap ;
4
+ import java .util .Map ;
5
+ import java .util .Objects ;
6
+
7
+ public final class CacheArraysFactory implements ArraysFactory {
8
+
9
+ private final Map <Key , int []> cache = new HashMap <>();
10
+ private final ArraysFactory arraysFactory ;
11
+
12
+ public CacheArraysFactory (final ArraysFactory arraysFactory ) {
13
+ this .arraysFactory = arraysFactory ;
14
+ }
15
+
16
+ @ Override
17
+ public int [] create (final int length ) {
18
+ final Key key = new Key (length );
19
+ int [] array = this .cache .get (key );
20
+ if (isEmpty (array )) {
21
+ array = this .arraysFactory .create (length );
22
+ this .cache .put (key , array );
23
+ }
24
+ return array ;
25
+ }
26
+
27
+ private boolean isEmpty (final int [] array ) {
28
+ return (array == null ) || (array .length == 0 );
29
+ }
30
+
31
+ private final class Key {
32
+
33
+ private final int value ;
34
+
35
+ Key (final int value ) {
36
+ this .value = value ;
37
+ }
38
+
39
+ @ Override
40
+ public boolean equals (final Object object ) {
41
+ if (this == object ) {
42
+ return true ;
43
+ }
44
+ if (object == null || getClass () != object .getClass ()) {
45
+ return false ;
46
+ }
47
+ final Key other = (Key ) object ;
48
+ return (this .value == other .value );
49
+ }
50
+
51
+ @ Override
52
+ public int hashCode () {
53
+ return Objects .hash (this .value );
54
+ }
55
+ }
56
+ }
You can’t perform that action at this time.
0 commit comments