系列文章目录
文章目录
前言
本笔记为B站尚硅谷Java入门视频教程(在线答疑+Java面试真题)的笔记,是笔者对于已经学过的大二Java课程的查缺补漏及巩固。部分C语言学过的基本语法将跳过。
十四、集合框架
1、Java集合框架体系
2、Collection接口中的方法的使用
package Test_2.collection;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
public class TestCollectionAdd {
@Test
public void testAdd(){
//ArrayList 是 Collection 的子接口 List 的实现类之一。
Collection coll = new ArrayList();
coll.add("小李广");
coll.add("扫地僧");
coll.add("石破天");
System.out.println(coll);
}
@Test
public void testAddAll(){
Collection c1 = new ArrayList();
c1.add(1);
c1.add(2);
System.out.println("c1 集合元素的个数:" + c1.size());//2
System.out.println("c1 = " + c1);
Collection c2 = new ArrayList();
c2.add(1);
c2.add(2);
System.out.println("c2 集合元素的个数:" + c2.size());//2
System.out.println("c2 = " + c2);
Collection other = new ArrayList();
other.add(1);
other.add(2);
other.add(3);
System.out.println("other 集合元素的个数:" + other.size());//3
System.out.println("other = " + other);
System.out.println();
c1.addAll(other);
System.out.println("c1 集合元素的个数:" + c1.size());//5
System.out.println("c1.addAll(other) = " + c1);
c2.add(other);
System.out.println("c2 集合元素的个数:" + c2.size());//3
System.out.println("c2.add(other) = " + c2);
}
}
判断:
package Test_2.collection;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
public class TestCollectionContains {
@Test
public void test01() {
Collection coll = new ArrayList();
System.out.println("coll 在添加元素之前,isEmpty = " + coll.isEmpty());
coll.add("小李广");
coll.add("扫地僧");
coll.add("石破天");
coll.add("佛地魔");
System.out.println("coll 的元素个数" + coll.size());
System.out.println("coll 在添加元素之后,isEmpty = " + coll.isEmpty());
}
@Test
public void test02() {
Collection coll = new ArrayList();
coll.add("小李广");
coll.add("扫地僧");
coll.add("石破天");
coll.add("佛地魔");
System.out.println("coll = " + coll);
System.out.println("coll 是否包含“小李广” = " + coll.contains("小李广"));
System.out.println("coll 是否包含“宋红康” = " + coll.contains("宋红康"));
Collection other = new ArrayList();
other.add("小李广");
other.add("扫地僧");
other.add("尚硅谷");
System.out.println("other = " + other);
System.out.println("coll.containsAll(other) = " + coll.containsAll(other));
}
@Test
public void test03(){
Collection c1 = new ArrayList();
c1.add(1);
c1.add(2);
System.out.println("c1 集合元素的个数:" + c1.size());//2
System.out.println("c1 = " + c1);
Collection c2 = new ArrayList();
c2.add(1);
c2.add(2);
System.out.println("c2 集合元素的个数:" + c2.size());//2
System.out.println("c2 = " + c2);
Collection other = new ArrayList();
other.add(1);
other.add(2);
other.add(3);
System.out.println("other 集合元素的个数:" + other.size());//3
System.out.println("other = " + other);
System.out.println();
c1.addAll(other);
System.out.println("c1 集合元素的个数:" + c1.size());//5
System.out.println("c1.addAll(other) = " + c1);
System.out.println("c1.contains(other) = " + c1.contains(other));
System.out.println("c1.containsAll(other) = " + c1.containsAll(other));
System.out.println();
c2.add(other);
System.out.println("c2 集合元素的个数:" + c2.size());
System.out.println("c2.add(other) = " + c2);
System.out.println("c2.contains(other) = " + c2.contains(other));
System.out.println("c2.containsAll(other) = " + c2.containsAll(other));
}
}
删除:
package Test_2.collection;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
public class TestCollectionRemove {
@Test
public void test01(){
Collection coll = new ArrayList();
coll.add("小李广");
coll.add("扫地僧");
coll.add("石破天");
coll.add("佛地魔");
System.out.println("coll = " + coll);
coll.remove("小李广");
System.out.println("删除元素\"小李广\"之后 coll = " + coll);
coll.clear();
System.out.println("coll 清空之后,coll = " + coll);
}
@Test
public void test02() {
Collection coll = new ArrayList();
coll.add("小李广");
coll.add("扫地僧");
coll.add("石破天");
coll.add("佛地魔");
System.out.println("coll = " + coll);
Collection other = new ArrayList();
other.add("小李广");
other.add("扫地僧");
other.add("尚硅谷");
System.out.println("other = " + other);
coll.removeAll(other);
System.out.println("coll.removeAll(other)之后,coll = " + coll);
System.out.println("coll.removeAll(other)之后,other = " + other);
}
@Test
public void test03() {
Collection coll = new ArrayList();
coll.add("小李广");
coll.add("扫地僧");
coll.add("石破天");
coll.add("佛地魔");
System.out.println("coll = " + coll);
Collection other = new ArrayList();
other.add("小李广");
other.add("扫地僧");
other.add("尚硅谷");
System.out.println("other = " + other);
coll.retainAll(other);
System.out.println("coll.retainAll(other)之后,coll = " + coll);
System.out.println("coll.retainAll(other)之后,other = " + other);
}
}
其他:
@Test
public void test01() {
Collection coll = new ArrayList();
coll.add("小李广");
coll.add("扫地僧");
coll.add("石破天");
coll.add("佛地魔");
//集合转换为数组:集合的 toArray()方法
Object[] objects = coll.toArray();
System.out.println("用数组返回 coll 中所有元素:" + Arrays.toString(objects));
//对应的,数组转换为集合:调用 Arrays 的 asList(Object ...objs)
Object[] arr1 = new Object[]{123,"AA","CC"};
Collection list = Arrays.asList(arr1);
System.out.println(list);
}
3、Iterator(迭代器)接口
package Test_2.collection;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class TestIterator {
@Test
public void test01(){
Collection coll = new ArrayList();
coll.add("小李广");
coll.add("扫地僧");
coll.add("石破天");
Iterator iterator = coll.iterator();
System.out.println(iterator.next());
System.out.println(iterator.next());
System.out.println(iterator.next());
System.out.println(iterator.next());//报 NoSuchElementException 异常
}
@Test
public void test02(){
Collection coll = new ArrayList();
coll.add("小李广");
coll.add("扫地僧");
coll.add("石破天");
Iterator iterator = coll.iterator();//获取迭代器对象
while (iterator.hasNext()){ //判断是否还有元素可迭代
System.out.println(iterator.next()); //取出下一个元素
}
}
}

使用 Iterator 迭代器删除元素
package Test_2.collection;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class TestIteratorRemove {
@Test
public void test01(){
Collection coll = new ArrayList();
coll.add(1);
coll.add(2);
coll.add(3);
coll.add(4);
coll.add(5);
coll.add(6);
Iterator iterator = coll.iterator();
while (iterator.hasNext()){
Integer element = (Integer) iterator.next();
if(element % 2 == 0){
iterator.remove();
}
}
System.out.println(coll);
}
}
package Test_2.collection;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
public class TestForeach {
@Test
public void test01(){
Collection coll = new ArrayList();
coll.add("小李广");
coll.add("扫地僧");
coll.add("石破天");
//foreach 循环其实就是使用 Iterator 迭代器来完成元素的遍历的。
for(Object obj : coll){
System.out.println(obj);
}
}
@Test
public void test02(){
int[] nums = {1, 2, 3, 4, 5};
for (int num : nums) {
System.out.println(num);
}
System.out.println("-------------");
String[] names = {"张三","李四","王五"};
for (String name : names) {
System.out.println(name);
}
}
}

4、Collection 子接口 1:List
package Test_2.collection;
import java.util.ArrayList;
import java.util.List;
public class TestListMethod {
public static void main(String[] args) {
// 创建 List 集合对象
List list = new ArrayList();
// 往 尾部添加 指定元素
list.add("图图");
list.add("小美");
list.add("不高兴");
System.out.println(list);
// add(int index,String s) 往指定位置添加
list.add(1,"没头脑");
System.out.println(list);
// String remove(int index) 删除指定位置元素 返回被删除元素
// 删除索引位置为 2 的元素
System.out.println("删除索引位置为 2 的元素");
System.out.println(list.remove(2));
System.out.println(list);
// String set(int index,String s)
// 在指定位置 进行 元素替代(改)
// 修改指定位置元素
list.set(0, "三毛");
System.out.println(list);
// String get(int index) 获取指定位置元素
// 跟 size() 方法一起用 来 遍历的
for(int i = 0;i<list.size();i++){
System.out.println(list.get(i));
}
//还可以使用增强 for
for (Object obj : list) {
System.out.println(obj);
}
}
}
5、Collection 子接口 2:Set
•HashSet 是 Set 接口的主要实现类,大多数时候使用 Set 集合时都使用这个实现 类。
package Test_2.collection;
import org.junit.Test;
import java.util.HashSet;
import java.util.Objects;
class MyDate{
private int year;
private int month;
private int day;
public MyDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof MyDate)) return false;
MyDate myDate = (MyDate) o;
return year == myDate.year &&
month == myDate.month &&
day == myDate.day;
}
@Override
public int hashCode() {
return Objects.hash(year, month, day);
}
@Override
public String toString() {
return "MyDate{" +
"year=" + year +
", month=" + month +
", day=" + day +
'}';
}
}
public class TestHashSet {
@Test
public void test01(){
HashSet set = new HashSet();
set.add("张三");
set.add("张三");
set.add("李四");
set.add("王五");
set.add("王五");
set.add("赵六");
System.out.println("set = " + set);//不允许重复,无序
}
@Test
public void test02(){
HashSet set = new HashSet();
set.add(new MyDate(2021,1,1));
set.add(new MyDate(2021,1,1));
set.add(new MyDate(2022,2,4));
set.add(new MyDate(2022,2,4));
System.out.println("set = " + set);//不允许重复,无序
}
}
package Test_2.collection;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class TestSet_1 {
public static List duplicateList(List list){
HashSet set = new HashSet();
set.addAll(list);
return new ArrayList(set);
}
public static void main(String[] args) {
List list = new ArrayList();
list.add(new Integer(1));
list.add(new Integer(2));
list.add(new Integer(2));
list.add(new Integer(4));
list.add(new Integer(4));
List list1 = duplicateList(list);
for(Object integer : list1){
System.out.println(integer);
}
}
}

•因为只有相同类的两个实例才会比较大小,所以向 TreeSet 中添加的应该是同一个 类的对象。
package Test_2.collection;
import org.junit.Test;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetTest {
/*
* 自然排序:针对 String 类的对象
* */
@Test
public void test01(){
TreeSet set = new TreeSet();
set.add("MM");
set.add("CC");
set.add("AA");
set.add("DD");
set.add("ZZ");
//set.add(123); //报 ClassCastException 的异常
Iterator iterator = set.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
/*
* 自然排序:针对 User 类的对象
* */
@Test
public void test02(){
TreeSet set = new TreeSet();
set.add(new User("Tom",12));
set.add(new User("Rose",23));
set.add(new User("Jerry",2));
set.add(new User("Eric",18));
set.add(new User("Tommy",44));
set.add(new User("Jim",23));
set.add(new User("Maria",18));
//set.add("Tom");
Iterator iterator = set.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println(set.contains(new User("Jim", 23))); //true
}
/*
* 定制排序
* */
@Test
public void test03() {
//按照 User 的姓名的从小到大的顺序排列
Comparator comparator = new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof User && o2 instanceof User){
User u1 = (User)o1;
User u2 = (User)o2;
return u1.name.compareTo(u2.name);
}
throw new RuntimeException("输入的类型不匹配");
}
};
TreeSet set = new TreeSet(comparator);
set.add(new User("Tom",12));
set.add(new User("Rose",23));
set.add(new User("Jerry",2));
set.add(new User("Eric",18));
set.add(new User("Tommy",44));
set.add(new User("Jim",23));
set.add(new User("Maria",18));
//set.add(new User("Maria",28));
Iterator iterator = set.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
class User implements Comparable{
String name;
int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
/*
举例:按照 age 从小到大的顺序排列,如果 age 相同,则按照 name 从大到小的顺序排列
* */
@Override
public int compareTo(Object o) {
if(this == o){
return 0;
}
if(o instanceof User){
User user = (User)o;
int value = this.age - user.age;
if(value != 0){
return value;
}
return -this.name.compareTo(user.name);
}
throw new RuntimeException("输入的类型不匹配");
}
}
6、Map接口

Map 中 key-value 特点


package Test_2.collection;
import org.junit.Test;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class TestMapMethod {
@Test
public void test01(){
HashMap map = new HashMap();
map.put("黄晓明", "杨颖");
map.put("李晨", "李小璐");
map.put("李晨", "范冰冰");
map.put("邓超", "孙俪");
System.out.println(map);
System.out.println(map.remove("黄晓明"));
System.out.println(map);
System.out.println(map.get("邓超"));
System.out.println(map.get("黄晓明"));
}
@Test
public void test02(){
HashMap map = new HashMap();
map.put("许仙", "白娘子");
map.put("董永", "七仙女");
map.put("牛郎", "织女");
map.put("许仙", "小青");
System.out.println("所有的 key:");
Set keySet = map.keySet();
for(Object key : keySet){
System.out.println(key);
}
System.out.println("所有的value:");
Collection values = map.values();
System.out.println(values);
for(Object value : values){
System.out.println(value);
}
System.out.println("所有的映射关系:");
Set entrySet = map.entrySet();
System.out.println(entrySet);
for(Object mapping : entrySet){
Map.Entry entry = (Map.Entry) mapping;
System.out.println(entry.getKey() + "->" + entry.getValue());
}
}
}
package Test_2.collection;
import org.junit.Test;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
public class TestLinkedHashMap {
@Test
public void test1(){
LinkedHashMap map = new LinkedHashMap();
map.put("王五", 13000.0);
map.put("张三", 10000.0);
//key 相同,新的 value 会覆盖原来的 value
//因为 String 重写了 hashCode 和 equals 方法
map.put("张三", 12000.0);
map.put("李四", 14000.0);
//HashMap 支持 key 和 value 为 null 值
String name = null;
Double salary = null;
map.put(name, salary);
System.out.println(map);
Set entrySet = map.entrySet();
for(Object obj : entrySet){
System.out.println(obj);
}
System.out.println("------------------");
for(Object obj : entrySet){
Map.Entry entry = (Map.Entry) obj;
System.out.println(entry);
}
}
}
package Test_2.collection;
import org.junit.Test;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeMap;
public class TestTreeMap {
/*
* 自然排序举例
* */
@Test
public void test1(){
TreeMap map = new TreeMap();
map.put("DD",26);
map.put("CC",45);
map.put("GG",89);
map.put("MM",78);
map.put("JJ",99);
Set entryset = map.entrySet();
for(Object entry : entryset){
System.out.println(entry);
}
System.out.println("--------------------");
TreeMap map1 = new TreeMap();
map1.put(new User("Tom",12),67);
map1.put(new User("Rose",23),"87");
map1.put(new User("Jerry",2),88);
map1.put(new User("Eric",18),45);
map1.put(new User("Tommy",44),77);
map1.put(new User("Jim",23),88);
map1.put(new User("Maria",18),34);
Set entryset1 = map1.entrySet();
for(Object o : entryset1){
System.out.println(o);
}
}
/*
* 定制排序
*
* */
@Test
public void test2(){
//按照 User 的姓名的从小到大的顺序排列
TreeMap map = new TreeMap(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof User && o2 instanceof User){
User u1 = (User)o1;
User u2 = (User)o2;
return u1.name.compareTo(u2.name);
}
throw new RuntimeException("输入的类型不匹配");
}
});
map.put(new User("Tom",12),67);
map.put(new User("Rose",23),"87");
map.put(new User("Jerry",2),88);
map.put(new User("Eric",18),45);
map.put(new User("Tommy",44),77);
map.put(new User("Jim",23),88);
map.put(new User("Maria",18),34);
Set entrySet = map.entrySet();
for(Object entry : entrySet){
System.out.println(entry);
}
}
}
class User implements Comparable{
String name;
int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public User() {
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
/*
举例:按照 age 从小到大的顺序排列,如果 age 相同,则按照 name 从大到小的顺序排列
* */
@Override
public int compareTo(Object o) {
if(this == o){
return 0;
}
if(o instanceof User){
User user = (User)o;
int value = this.age - user.age;
if(value != 0){
return value;
}
return -this.name.compareTo(user.name);
}
throw new RuntimeException("输入的类型不匹配");
}
}
7、Collections 工具类
package Test_2.collection;
import org.junit.Test;
import java.util.*;
public class TestCollections {
@Test
public void test01(){
Collection<Object> coll = new ArrayList<>();
Collections.addAll(coll,"hello","Java");
Collections.addAll(coll, 1234, 1, 2);
System.out.println(coll);
Collection<String> coll2 = new ArrayList<>();
Collections.addAll(coll2, "hello ", "world");
System.out.println(coll2);
}
@Test
public void test02(){
List<Man> list = new ArrayList<>();
list.add(new Man("张三", 16));
list.add(new Man("李四", 17));
list.add(new Man("王五", 18));
/*
* Man max = Collections.max(list);//要求 Man 实现 Comparable 接口,或者父类实现
*/
Man max = Collections.max(list, new Comparator<Man>() {
@Override
public int compare(Man o1, Man o2) {
return o1.getAge()-o2.getAge();
}
});
System.out.println(max);
}
}
class Man implements Comparable{
String name;
int age;
public Man(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Man{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Object o) {
return 0;
}
}
十五、泛型
1、泛型概述
Java中的泛型,就类似于生活场景中出现的用于分类的那种标签。

2、集合中使用泛型
package Test_2.generic;
import org.junit.Test;
import java.util.*;
public class genericTest1 {
//泛型在 List 中的使用
@Test
public void test1(){
//举例:将学生成绩保存在 ArrayList 中
//标准写法:
//ArrayList<Integer> list = new ArrayList<Integer>();
//jdk7 的新特性:类型推断
ArrayList<Integer> list = new ArrayList<>();
list.add(56);//自动装箱
list.add(76);
list.add(88);
list.add(89);
//当添加非 Integer 类型数据时,编译不通过
//list.add("Tom");//编译报错
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()){
//不需要强转,直接可以获取添加时的元素的数据类型
Integer score = iterator.next();
System.out.println(score);
}
}
//泛型在 Map 中的使用
@Test
public void test2(){
HashMap<String, Integer> map = new HashMap<>();
map.put("Tom",67);
map.put("Jim",56);
map.put("Rose",88);
//编译不通过
// map.put(67,"Jack");
//遍历 key 集
Set<String> keySet = map.keySet();
for(String str : keySet){
System.out.println(str);
}
//遍历 value 集
Collection<Integer> values = map.values();
for(Integer val : values){
System.out.println(val);
}
//遍历 entry 集
Set<Map.Entry<String,Integer>> entrySet = map.entrySet();
for(Map.Entry entry : entrySet){
System.out.println(entry);
}
}
}
3、比较器中使用泛型
package com . atguigu . generic ;public class Circle {private double radius ;public Circle ( double radius ) {super ();this . radius = radius ;}public double getRadius () {return radius ;}public void setRadius ( double radius ) {this . radius = radius ;}@Overridepublic String toString () {return "Circle [radius=" + radius + "]" ;}}使用泛型之前:package com . atguigu . generic ;import java . util . Comparator ;class CircleComparator implements Comparator {@Overridepublic int compare ( Object o1 , Object o2 ) {// 强制类型转换Circle c1 = ( Circle ) o1 ;Circle c2 = ( Circle ) o2 ;return Double . compare ( c1 . getRadius (), c2 . getRadius ()); }}// 测试:public class TestNoGeneric {public static void main ( String [] args ) {CircleComparator com = new CircleComparator ();System . out . println ( com . compare ( new Circle ( 1 ), new Circle( 2 )));System . out . println ( com . compare ( " 圆 1" , " 圆 2" )); // 运行时异常: ClassCastException}}使用泛型之后:package com . atguigu . generic ;import java . util . Comparator ;class CircleComparator1 implements Comparator < Circle > {@Overridepublic int compare ( Circle o1 , Circle o2 ) {// 不再需要强制类型转换,代码更简洁return Double . compare ( o1 . getRadius (), o2 . getRadius ());}}// 测试类public class TestHasGeneric {public static void main ( String [] args ) {CircleComparator1 com = new CircleComparator1 ();System . out . println ( com . compare ( new Circle ( 1 ), new Circle( 2 )));//System.out.println(com.compare(" 圆 1", " 圆 2"));// 编译错误,因为 " 圆 1", " 圆 2" 不是 Circle 类型,是 String 类型,编译器提前报错,// 而不是冒着风险在运行时再报错。}}
4、自定义泛型结构
-
尖括号 <> 中的 泛型标识被称作是
类型参数,用于指代任何数据类型。 -
泛型标识是任意设置的(如果你想可以设置为 Hello都行),Java 常见的泛型标识以及其代表含义如下:
T :代表一般的任何类。
E :代表 Element 元素的意思,或者 Exception 异常的意思。
K :代表 Key 的意思。
V :代表 Value 的意思,通常与 K 一起配合使用。
S :代表 Subtype 的意思
class Person<T> {
// 使用 T 类型定义变量
private T info;
// 使用 T 类型定义一般方法
public T getInfo() {
return info;
}
public void setInfo(T info) {
this.info = info;
}
// 使用 T 类型定义构造器
public Person() {
}
public Person(T info) {
this.info = info;
}
// static 的方法中不能声明泛型
//public static void show(T t) {
//
//}
// 不能在 try-catch 中使用泛型定义
//public void test() {
//try {
//
//} catch (MyException<T> ex) {
//
//}
//}
}
class Father<T1, T2> {
}
// 子类不保留父类的泛型
// 1)没有类型 擦除
class Son1 extends Father {// 等价于 class Son extends Father<Object,O
bject>{
}
// 2)具体类型
class Son2 extends Father<Integer, String> {
}
// 子类保留父类的泛型
// 1)全部保留
class Son3<T1, T2> extends Father<T1, T2> {
}
// 2)部分保留
class Son4<T2> extends Father<Integer, T2> {
}
class Father<T1, T2> {
}
// 子类不保留父类的泛型
// 1)没有类型 擦除
class Son<A, B> extends Father{//等价于 class Son extends Father<Objec
t,Object>{
}
// 2)具体类型
class Son2<A, B> extends Father<Integer, String> {
}
// 子类保留父类的泛型
// 1)全部保留
class Son3<T1, T2, A, B> extends Father<T1, T2> {
}
// 2)部分保留
class Son4<T2, A, B> extends Father<Integer, T2> {
}
public class DAO {
public <E> E get(int id, E e) {
E result = null;
return result;
}
}
public static <T> void fromArrayToCollection(T[] a, Collection<T> c)
{
for (T o : a) {
c.add(o);
}
}
public static void main(String[] args) {
Object[] ao = new Object[100];
Collection<Object> co = new ArrayList<Object>();
fromArrayToCollection(ao, co);
String[] sa = new String[20];
Collection<String> cs = new ArrayList<>();
fromArrayToCollection(sa, cs);
Collection<Double> cd = new ArrayList<>();
// 下面代码中 T 是 Double 类,但 sa 是 String 类型,编译错误。
// fromArrayToCollection(sa, cd);
// 下面代码中 T 是 Object 类型,sa 是 String 类型,可以赋值成功。
fromArrayToCollection(sa, co);
}
举例3:
class MyArrays {
public static <T> void sort(T[] arr){
for (int i = 1; i < arr.length; i++) {
for (int j = 0; j < arr.length-i; j++) {
if(((Comparable<T>)arr[j]).compareTo(arr[j+1])>0){
T temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
}
public class MyArraysTest {
public static void main(String[] args) {
int[] arr = {3,2,5,1,4};
// MyArrays.sort(arr);//错误的,因为 int[]不是对象数组
String[] strings = {"hello","java","song"};
MyArrays.sort(strings);
System.out.println(Arrays.toString(strings));
Circle[] circles = {new Circle(2.0),new Circle(1.2),new Circl
e(3.0)};
MyArrays.sort(circles); //编译通过,运行报错,因为 Circle 没有实现 Comparable 接口
}
}
5、泛型在继承上的体现
public void testGenericAndSubClass() {
Person[] persons = null;
Man[] mans = null;
//Person[] 是 Man[] 的父类
persons = mans;
Person p = mans[0];
// 在泛型的集合上
List<Person> personList = null;
List<Man> manList = null;
//personList = manList;(报错)
}
6、通配符的使用
public class TestWildcard {
public static void m4(Collection<?> coll){
for (Object o : coll) {
System.out.println(o);
}
}
}
public static void main(String[] args) {
List<?> list = null;
list = new ArrayList<String>();
list = new ArrayList<Double>();
// list.add(3);//编译不通过
list.add(null);
List<String> l1 = new ArrayList<String>();
List<Integer> l2 = new ArrayList<Integer>();
l1.add("尚硅谷");
l2.add(15);
read(l1);
read(l2);
}
public static void read(List<?> list) {
for (Object o : list) {
System.out.println(o);
}
}
class Creature{}
class Person extends Creature{}
class Man extends Person{}
class PersonTest {
public static <T extends Person> void test(T t){
System.out.println(t);
}
public static void main(String[] args) {
test(new Person());
test(new Man());
//The method test(T) in the type PersonTest is not
//applicable for the arguments (Creature)
test(new Creature());
}
}
public static void main(String[] args) {
Collection<Integer> list1 = new ArrayList<Integer>();
Collection<String> list2 = new ArrayList<String>();
Collection<Number> list3 = new ArrayList<Number>();
Collection<Object> list4 = new ArrayList<Object>();
getElement1(list1);
getElement1(list2);//报错
getElement1(list3);
getElement1(list4);//报错
getElement2(list1);//报错
getElement2(list2);//报错
getElement2(list3);
getElement2(list4);
}
// 泛型的上限:此时的泛型?,必须是 Number 类型或者 Number 类型的子类
public static void getElement1(Collection<? extends Number> col
l){}
// 泛型的下限:此时的泛型?,必须是 Number 类型或者 Number 类型的父类
public static void getElement2(Collection<? super Number> coll)
{}
public static void printCollection1(Collection<? extends Person> coll) {
//Iterator 只能用 Iterator<?>或 Iterator<? extends Person>.why?
Iterator<?> iterator = coll.iterator();
while (iterator.hasNext()) {
Person per = iterator.next();
System.out.println(per);
}
}
public static void printCollection2(Collection<? super Person > coll) {
//Iterator 只能用 Iterator<?>或 Iterator<? super Person>.why?
Iterator<?> iterator = coll.iterator();
while (iterator.hasNext()) {
Object obj = iterator.next();
System.out.println(obj);
}
}
1090



被折叠的 条评论
为什么被折叠?



