Skip to content

Commit f046e01

Browse files
author
turingfly
committed
Generics and Collections
1 parent 9f39a32 commit f046e01

14 files changed

+650
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package genericsAndCollections;
2+
3+
import java.util.Arrays;
4+
import java.util.List;
5+
6+
/**
7+
*
8+
* @author chengfeili
9+
* Jun 7, 2017 5:06:24 PM
10+
*
11+
* An ArrayList cannot contain primitives.
12+
* An Array can contain objects and primitives.
13+
*/
14+
public class ArrayAndArrayList {
15+
public void test() {
16+
String[] array = { "a", "b" }; // [a, b]
17+
// convert an Array to a List
18+
List<String> list = Arrays.asList(array); // [a, b]
19+
// You can change the element in either the array or the list.
20+
// Changes are reflected in both, since they are backed by the same data.
21+
array[0] = "c";
22+
// convert a List to an Array
23+
24+
String[] array2 = (String[]) list.toArray(); // [c, b]
25+
26+
// list.remove(1); throws UnsupportedOperationException
27+
// list is not resizable because it is backed by the underlying array.
28+
}
29+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package genericsAndCollections;
2+
3+
import java.util.Comparator;
4+
5+
/**
6+
*
7+
* @author chengfeili
8+
* Jun 7, 2017 9:22:16 PM
9+
*
10+
*/
11+
12+
public class ComparingMultipleFields implements Comparator<Squirrel> {
13+
public int compare(Squirrel s1, Squirrel s2) {
14+
Comparator<Squirrel> c = Comparator.comparing(s -> s.getSpecies());
15+
c = c.thenComparingInt(s -> s.getWeight());
16+
return c.compare(s1, s2);
17+
}
18+
}
19+
20+
class Squirrel {
21+
private int weight;
22+
private String species;
23+
24+
public Squirrel(String theSpecies) {
25+
if (theSpecies == null)
26+
throw new IllegalArgumentException();
27+
species = theSpecies;
28+
}
29+
30+
public int getWeight() {
31+
return weight;
32+
}
33+
34+
public void setWeight(int weight) {
35+
this.weight = weight;
36+
}
37+
38+
public String getSpecies() {
39+
return species;
40+
}
41+
}
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
package genericsAndCollections;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
/**
7+
*
8+
* @author chengfeili
9+
* Jun 7, 2017 6:12:41 PM
10+
*
11+
* A bounded parameter type is a generic type that specifies a bound for
12+
* the generic. A wildcard generic type is an unknown generic type
13+
* represented with a question mark ( ? ).
14+
*
15+
* class A {}
16+
* class B extends A { }
17+
* class C extends B { }
18+
*
19+
* List<?> list1 = new ArrayList<A>();
20+
* List<? extends A> list2 = new ArrayList<A>();
21+
* List<? super A> list3 = new ArrayList<A>();
22+
* List<? extends B> list4 = new ArrayList<A>(); It has an upper-bounded wildcard that allows ArrayList<B> or ArrayList<C> to be referenced.
23+
* List<? super B> list5 = new ArrayList<A>();
24+
* List<?> list6 = new ArrayList<? extends A>(); The problem is that you need to know what
25+
* that type will be when instantiating the ArrayList.
26+
*
27+
*/
28+
public class GenericBound {
29+
/*
30+
* We can’t write List<Object> l = new ArrayList<String>(); because Java is
31+
* trying to protect us from a runtime exception.
32+
*/
33+
public static void printList(List<Object> list) {
34+
for (Object x : list)
35+
System.out.println(x);
36+
}
37+
38+
// 1. Unbounded Wildcards
39+
public static void printList1(List<?> list) {
40+
for (Object x : list)
41+
System.out.println(x);
42+
}
43+
44+
/**
45+
* 2. Upper-Bounded Wildcards
46+
* The upper-bounded wildcard says that any class
47+
* that extends Number or Number itself can be used as the formal parameter type:
48+
*
49+
* static class Sparrow extends Bird { }
50+
* static class Bird { }
51+
* public static void main(String[] args) {
52+
* List<? extends Bird> birds = new ArrayList <Bird>();
53+
* birds.add(new Sparrow()); // DOES NOT COMPILE birds.add(new
54+
* Bird()); // DOES NOT COMPILE
55+
*
56+
* The problem stems from the fact that Java doesn’t know what type List<?
57+
* extends Bird> really is. It could be List<Bird> or List<Sparrow> or some
58+
* other generic type that hasn’t even been written yet. Line 7 doesn’t
59+
* compile because we can’t add a Sparrow to List<Bird> , and line 8 doesn’t
60+
* compile because we can’t add a Bird to List<Sparrow> .
61+
*
62+
* private void groupOfFlyers(List<? extends Flyer> flyer) {}Note that we
63+
* used the keyword extends rather than implements .
64+
*/
65+
public static long total(List<? extends Number> list) {
66+
67+
// ArrayList<Number> list = new ArrayList<Integer>(); // DOES NOT
68+
// COMPILE
69+
long count = 0;
70+
for (Number number : list)
71+
count += number.longValue();
72+
return count;
73+
}
74+
75+
// 3. Lower-Bounded Wildcards
76+
public static void addSound(List<? super String> list) {
77+
list.add("quack");
78+
}
79+
80+
public static void main(String[] args) {
81+
List<String> keywords = new ArrayList<>();
82+
keywords.add("java");
83+
// printList(keywords); Does not compile
84+
// List<String> cannot be assigned to List<Object>
85+
printList1(keywords);
86+
}
87+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package genericsAndCollections;
2+
3+
/**
4+
*
5+
* @author chengfeili Jun 7, 2017 5:44:24 PM
6+
*
7+
* When you instantiate the class, you tell the compiler what T
8+
* should be for that particular instance.
9+
*/
10+
public class GenericClass<T> {
11+
private T contents;
12+
13+
public T emptyCrate() {
14+
return contents;
15+
}
16+
17+
public void packCrate(T contents) {
18+
this.contents = contents;
19+
}
20+
// Generic Method
21+
public static <T> GenericClass<T> ship(T t) {
22+
System.out.println("Preparing " + t);
23+
return new GenericClass<T>();
24+
}
25+
}
26+
27+
class SizeLimitedCrate<T, U> {
28+
private T contents;
29+
private U sizeLimit;
30+
31+
public SizeLimitedCrate(T contents, U sizeLimit) {
32+
this.contents = contents;
33+
this.sizeLimit = sizeLimit;
34+
}
35+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package genericsAndCollections;
2+
3+
/**
4+
*
5+
* @author chengfeili
6+
* Jun 7, 2017 5:47:33 PM
7+
*
8+
* 3 ways a class can approach implementing this interface
9+
*
10+
* Here are the things that you can’t do with generics. (And by “can’t,”
11+
* we mean without resorting to contortions like passing in a class
12+
* object.)
13+
* 1. Call the constructor. new T() is not allowed because at
14+
* runtime it would be new Object() .
15+
* 2. Create an array of that static type. This one is the most annoying, but it makes sense
16+
* because you’d be creating an array of Object s.
17+
* 3. Call instanceof . This is not allowed because at runtime List<Integer> and List
18+
* <String> look the same to Java thanks to type erasure.
19+
* 4.Use a primitive type as a generic type parameter. This isn’t a big deal
20+
* because you can use the wrapper class instead. If you want a type of
21+
* int , just use Integer.
22+
* 5. Create a static variable as a generic type parameter.
23+
* This is not allowed because the type is linked to the
24+
* instance of the class.
25+
*/
26+
public interface GenericInterface<T> {
27+
void ship(T t);
28+
}
29+
30+
class Robot {
31+
32+
}
33+
34+
// Method 1: specify the generic type in the class
35+
class ShippableRobotCrate implements GenericInterface<Robot> {
36+
public void ship(Robot t) {
37+
}
38+
}
39+
40+
// Method 2: create a generic class
41+
class ShippableAbstractCrate<U> implements GenericInterface<U> {
42+
public void ship(U t) {
43+
}
44+
}
45+
46+
// Method 3: not use generics at all.
47+
class ShippableCrate implements GenericInterface {
48+
public void ship(Object t) {
49+
}
50+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package genericsAndCollections;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.Collections;
6+
import java.util.Comparator;
7+
import java.util.List;
8+
9+
/**
10+
*
11+
* @author chengfeili
12+
* Jun 7, 2017 5:19:13 PM
13+
*
14+
*
15+
*/
16+
public class SearchingAndSorting {
17+
static class A {
18+
int id;
19+
}
20+
public void test() {
21+
int[] nums = {6, 9, 1, 8};
22+
Arrays.sort(nums); // [1, 6, 8, 9]
23+
System.out.println(Arrays.binarySearch(nums, 6)); // 1
24+
System.out.println(Arrays.binarySearch(nums, 3)); // -2 ( -1 -1 )
25+
}
26+
public void test2() {
27+
List<A> list = new ArrayList<>();
28+
list.add(new A());
29+
// Collections.sort(list); Does not compile
30+
Comparator<A> c = (a, b) -> a.id - b.id;
31+
Collections.sort(list, c);
32+
33+
}
34+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package genericsAndCollections;
2+
3+
import java.util.ArrayList;
4+
import java.util.Collections;
5+
import java.util.List;
6+
7+
/**
8+
*
9+
* @author chengfeili
10+
* Jun 7, 2017 8:56:49 PM
11+
*
12+
*/
13+
public class UsingComparable implements Comparable<UsingComparable> {
14+
15+
private String name;
16+
17+
public UsingComparable(String name) {
18+
// TODO Auto-generated constructor stub
19+
this.name = name;
20+
}
21+
22+
public String toString() {
23+
return name;
24+
}
25+
26+
@Override
27+
public int compareTo(UsingComparable o) {
28+
// TODO Auto-generated method stub
29+
return name.compareTo(o.name); // call String's compareTo
30+
}
31+
32+
public static void main(String[] args) {
33+
List<UsingComparable> list = new ArrayList<>();
34+
list.add(new UsingComparable("b"));
35+
list.add(new UsingComparable("a"));
36+
Collections.sort(list); // sort by name
37+
System.out.println(list); // [a, b]
38+
}
39+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package genericsAndCollections;
2+
3+
/**
4+
*
5+
* @author chengfeili
6+
* Jun 7, 2017 9:07:21 PM
7+
*
8+
* Remember that id – a.id sorts in ascending order and a.id – id sorts
9+
* in descending order.
10+
*/
11+
public class UsingComparable1 implements Comparable<UsingComparable1> {
12+
private int id;
13+
14+
public int compareTo(UsingComparable1 a) {
15+
return id - a.id;
16+
}
17+
18+
public static void main(String[] args) {
19+
UsingComparable1 a1 = new UsingComparable1();
20+
UsingComparable1 a2 = new UsingComparable1();
21+
a1.id = 5;
22+
a2.id = 7;
23+
System.out.println(a1.compareTo(a2)); // -2
24+
System.out.println(a1.compareTo(a1)); // 0
25+
System.out.println(a2.compareTo(a1)); // 2
26+
}
27+
}

0 commit comments

Comments
 (0)