5.1、泛型

概述:泛型是是JDK5中引入的特性,它提供了编译时类型安全检测机制,该机制允许在编译时检测到非法的类型,它的本质是参数化类型,也就是说所操作的数据类型被指定为一个参数。

泛型类:

// 格式:修饰符 class 类名<类型> { }
class Generic<T> {
private T t; public T getT() {
return t;
} public void setT(T t) {
this.t = t;
}
} public class Main {
public static void main(String[] args) {
Generic<String> g1 = new Generic<String>();
g1.setT("String");
System.out.println(g1.getT());
Generic<Integer> g2 = new Generic<Integer>();
g2.setT(100);
System.out.println(g2.getT());
Generic<Boolean> g3 = new Generic<Boolean>();
g3.setT(true);
System.out.println(g3.getT());
}
}

泛型方法:

// 格式:修饰符 <类型> 返回值类型 方法名(类型 变量名) { }
class Generic {
public <T> void show(T t) {
System.out.println(t);
}
} public class Main {
public static void main(String[] args) {
Generic g = new Generic();
g.show("String");
g.show(100);
g.show(true);
}
}

泛型接口:

// 修饰符 interface 接口名<类型> { }
interface Generic<T> {
void show(T t);
} class GenericImpl<T> implements Generic<T> {
@Override
public void show(T t) {
System.out.println(t);
}
} public class Main {
public static void main(String[] args) {
Generic<String> g1 = new GenericImpl<String>();
g1.show("String");
Generic<Integer> g2 = new GenericImpl<Integer>();
g2.show(30);
Generic<Boolean> g3 = new GenericImpl<Boolean>();
g3.show(true);
}
}

类型通配符:

类型通配符:<?>
List<?>:表示元素类型未知的List,它的元素可以匹配任何的类型 类型通配符上限:<? extends 类型>
List<? extends Number>:它表示的类型是Number或者其子类型 类型通配符下限:<? super 类型>
List<? super Number>:它表示的类型是Number或者其父类型

可变参数:

public class Main {
public static void main(String[] args) {
System.out.println(sum(10));
System.out.println(sum(10, 20));
System.out.println(sum(10, 20, 30));
System.out.println(sum(10, 20, 30, 40));
System.out.println(sum(10, 20, 30, 40, 50));
System.out.println(sum(10, 20, 30, 40, 50, 60));
System.out.println(sum(10, 20, 30, 40, 50, 60, 70));
System.out.println(sum(10, 20, 30, 40, 50, 60, 70, 80));
System.out.println(sum(10, 20, 30, 40, 50, 60, 70, 80, 90));
System.out.println(sum(10, 20, 30, 40, 50, 60, 70, 80, 90, 100));
} // 格式:修饰符 返回值类型 方法名(数据类型… 变量名) { }
public static int sum(int... a) {
int sum = 0;
for (int i : a) {
sum += i;
}
return sum;
}
}

5.2、集合

概述:提供一种可变的存储模型,存储的数据容量可以随时发生改变

体系:

5.2.1、Collection接口

子接口特点:

  1. List接口:按照顺序存取,元素可以重复,有索引,可使用迭代器、增强for循环、普通for循环遍历
  2. Set接口:不按照顺序存取,元素不可以重复,没有索引,可使用迭代器、增强for循环遍历

通用方法:

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator; public class Main {
public static void main(String[] args) {
// 创建集合
Collection<String> collection = new ArrayList<String>(); // 添加元素
collection.add("张三");
collection.add("张三");
collection.add("李四");
collection.add("李四");
collection.add("王五");
collection.add("王五");
System.out.println(collection.toString()); // 移除元素
collection.remove("张三");
System.out.println(collection.toString()); // 判断元素
boolean isContains = collection.contains("李四");
System.out.println(isContains); // 判断集合是否为空
boolean isEmpty = collection.isEmpty();
System.out.println(isEmpty); // 获取集合元素个数
int size = collection.size();
System.out.println(size); // 用迭代器遍历集合
Iterator<String> iterator = collection.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
} // 用增强for循环遍历
for (String s : collection) {
System.out.println(s);
} // 添加另外集合元素
Collection<String> c = new ArrayList<String>();
c.add("小可爱");
c.add("大可爱");
collection.addAll(c);
System.out.println(collection.toString()); // 清空集合所有元素
collection.clear();
System.out.println(collection.toString());
}
}

5.2.2、List接口

子类特点:

  1. ArrayList集合:底层是数组结构实现,查询快、增删慢
  2. LinkedList集合:底层是链表结构实现,查询慢、增删快

通用方法:

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator; public class Main {
public static void main(String[] args) {
// 创建集合
List<String> list = new ArrayList<String>(); // 添加元素
list.add("张三");
list.add("张三");
list.add("李四");
list.add("李四");
list.add("王五");
list.add("王五");
System.out.println(list.toString()); // List独有方法:E get(int index)
String s = list.get(0);
System.out.println(s); // List独有方法:E set(int index, E element)
list.set(2, "xiaoqi");
System.out.println(list.toString()); // List独有方法:ListIterator<E> listIterator()
ListIterator<String> listIterator = list.listIterator();
// 使用列表迭代器:从前向后迭代
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
// 使用列表迭代器:从后向前迭代
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
} // List独有遍历:普通for循环遍历
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}

注意事项:

LinkedList集合的特有方法:

方法 说明
public void addFirst(E e) 在该列表开头插入指定的元素
public void addLast(E e) 在该列表末尾追加指定的元素
public E getFirst() 返回此列表中的第一个元素
public E getLast() 返回此列表中的最后一个元素
public E removeFirst() 从此列表中删除并返回第一个元素
public E removeLast() 从此列表中删除并返回最后一个元素

5.2.3、Set接口

子类特点:

  1. HashSet集合:底层由哈希表支撑,元素存取无序,对象添加需要重写hashCode和equals方法
  2. TreeSet集合:底层由二叉树支撑,元素顺序存取,对象排序需要继承Comparable接口重写compareTo方法、或者使用Comparator初始化

HashSet演示:

import java.util.Collection;
import java.util.HashSet; class Student {
private String name;
private Integer age; public Student() {
super();
} public Student(String name, Integer age) {
super();
this.name = name;
this.age = age;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} @Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
} @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((age == null) ? 0 : age.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
} @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age == null) {
if (other.age != null)
return false;
} else if (!age.equals(other.age))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
} public class Main {
public static void main(String[] args) {
// 创建集合
Collection<Student> collection = new HashSet<Student>(); // 添加元素
collection.add(new Student("张三", 20));
collection.add(new Student("张三", 20));
collection.add(new Student("李四", 21));
collection.add(new Student("李四", 21));
collection.add(new Student("王五", 22));
collection.add(new Student("王五", 22));
System.out.println(collection.toString());
}
}

TreeSet演示:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序

import java.util.Collection;
import java.util.Comparator;
import java.util.TreeSet; class Student {
private String name;
private Integer age; public Student() {
super();
} public Student(String name, Integer age) {
super();
this.name = name;
this.age = age;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} @Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
} public class Main {
public static void main(String[] args) {
// 创建集合
Collection<Student> collection = new TreeSet<Student>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
// 主要条件
int sort1 = s1.getAge() - s2.getAge();
// 次要条件
int sort2 = sort1 == 0 ? s1.getName().compareTo(s2.getName()) : sort1;
return sort2;
}
}); // 添加元素
collection.add(new Student("王五", 22));
collection.add(new Student("王五", 22));
collection.add(new Student("张三1", 20));
collection.add(new Student("张三0", 20));
collection.add(new Student("李四0", 18));
collection.add(new Student("李四1", 18));
System.out.println(collection.toString());
}
}

5.2.4、Map接口

接口特点:

  1. 键值对映射关系
  2. 一个键对应一个值,键不可以重复,值可以重复
  3. 凡是对象作为HashMap的键时,对象添加需要重写hashCode和equals方法

通用方法:

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; public class Main {
public static void main(String[] args) {
// 创建集合
Map<String, String> map = new HashMap<String, String>(); // 添加元素
map.put("吕布", "貂蝉");
map.put("项羽", "虞姬");
map.put("郭靖", "黄蓉");
map.put("后裔", "嫦娥");
System.out.println(map.toString()); // 删除元素
map.remove("郭靖");
System.out.println(map.toString()); // 判断集合是否包含指定键
boolean containsKey = map.containsKey("吕布");
System.out.println(containsKey); // 判断集合是否包含指定值
boolean containsValue = map.containsValue("貂蝉");
System.out.println(containsValue); // 判断集合是否为空
boolean isEmpty = map.isEmpty();
System.out.println(isEmpty); // 获取集合元素个数
int size = map.size();
System.out.println(size); // 清空集合所有元素
map.clear();
System.out.println(map.toString()); // 添加另外集合元素
Map<String, String> m = new HashMap<String, String>();
m.put("张三", "李四");
m.put("王五", "小六");
map.putAll(m);
System.out.println(map.toString()); // 根据键获取值
System.out.println(map.get("张三")); // 获取所有键的集合
Set<String> keySet = map.keySet();
// 迭代器遍历
Iterator<String> keysIterator = keySet.iterator();
while (keysIterator.hasNext()) {
System.out.println(keysIterator.next());
}
// 增强for遍历
for (String key : keySet) {
System.out.println(key);
} // 获取所有值的集合
Collection<String> values = map.values();
// 迭代器遍历
Iterator<String> valuesIterator = values.iterator();
while (valuesIterator.hasNext()) {
System.out.println(valuesIterator.next());
}
// 增强for遍历
for (String value : values) {
System.out.println(value);
} // 获取所有键值对对象的集合
Set<Entry<String, String>> entrySet = map.entrySet();
// 迭代器遍历
Iterator<Entry<String, String>> entrySetIterator = entrySet.iterator();
while (entrySetIterator.hasNext()) {
Entry<String, String> entry = entrySetIterator.next();
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + ":" + value);
}
// 增强for遍历
for (Entry<String, String> entry : entrySet) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println(key + ":" + value);
}
}
}

5.3、Collections类

描述:是针对集合操作的工具类

成员方法:

方法 描述
public static void sort(List list) 将指定的列表按升序排序
public static void reverse(List list) 反转指定列表中元素的顺序
public static void shuffle(List list) 使用默认的随机源随机排列指定的列表

示例代码:斗地主洗牌

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.TreeSet; public class Main {
public static void main(String[] args) {
// 创建HashMap,键是编号,值是牌面
HashMap<Integer, String> hm = new HashMap<Integer, String>();
// 创建ArrayList,存储编号
ArrayList<Integer> array = new ArrayList<Integer>();
// 创建花色数组和点数数组
String[] colors = { "", "", "", "" };
String[] numbers = { "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2" };
// 从0开始往HashMap里面存储编号并存储对应的牌面,同时往ArrayList里面存储编号
int index = 0;
for (String number : numbers) {
for (String color : colors) {
hm.put(index, color + number);
array.add(index);
index++;
}
}
hm.put(index, "小王");
array.add(index);
index++;
hm.put(index, "大王");
array.add(index);
// 洗牌(洗的是编号)
Collections.shuffle(array);
// 发牌(发的是编号)
TreeSet<Integer> playerSet1 = new TreeSet<Integer>();
TreeSet<Integer> playerSet2 = new TreeSet<Integer>();
TreeSet<Integer> playerSet3 = new TreeSet<Integer>();
TreeSet<Integer> dpSet = new TreeSet<Integer>();
for (int i = 0; i < array.size(); i++) {
int x = array.get(i);
if (i >= array.size() - 3) {
dpSet.add(x);
} else if (i % 3 == 0) {
playerSet1.add(x);
} else if (i % 3 == 1) {
playerSet2.add(x);
} else if (i % 3 == 2) {
playerSet3.add(x);
}
}
// 调用看牌方法
lookPoker("player1", playerSet1, hm);
lookPoker("player2", playerSet2, hm);
lookPoker("player3", playerSet3, hm);
lookPoker("dp", dpSet, hm);
} /**
* 看牌方法
* @param name 玩家名称
* @param ts 牌面编号
* @param hm 牌面集合
*/
public static void lookPoker(String name, TreeSet<Integer> ts, HashMap<Integer, String> hm) {
System.out.print(name + ": ");
for (Integer key : ts) {
String poker = hm.get(key);
System.out.print(poker + " ");
}
System.out.println();
}
}

第五章 泛型&集合的更多相关文章

  1. [Effective Java]第五章 泛型

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

  2. 【读书笔记】C#高级编程 第五章 泛型

    (一)泛型概述 泛型不仅是C#编程语言的一部分,而且与程序集中的IL代码紧密地集成.泛型不仅是C#语言的一种结构,而且是CLR定义的.有了泛型就可以创建独立于被包含类型的类和方法了. 1.性能 泛型的 ...

  3. 第三章泛型集合ArrayList 和Hashtable

    第三章泛型集集合 ArrayList 变量名 = new ArrayList();  //相当与一个容器 他的执行using 是  using System.Collections; 变量名.ADD( ...

  4. C#高级编程学习一-----------------第五章泛型

    三层架构之泛型应用 概述 1.命名约定 泛型类型以T开头或就是T. 2.泛型类 2.1.创建泛型类

  5. 《Java编程思想》笔记 第十五章 泛型

    1 泛型 “泛型”意思就是适用于许多类型. 使用泛型的目的之一: 指定容器持有什么类型,让编译器确保正确性,而不是在运行期发现错误. 这个容器可以看成是有其他类型对象作为成员的类,而不单单只是JDK中 ...

  6. Programming Entity Framework-dbContext 学习笔记第五章

    ### Programming Entity Framework-dbContext 学习笔记 第五章 将图表添加到Context中的方式及容易出现的错误 方法 结果 警告 Add Root 图标中的 ...

  7. 【深入学习.Net】.泛型集合【体检管理系统】

    基于泛型List的体检管理系统(蜗牛爬坡) 第五章[体检管理系统] 一.项目展示图(基于.net core6.0) 二.首先准备两个Model类 HealthCheckItem(项目类):Name(项 ...

  8. 《Entity Framework 6 Recipes》中文翻译系列 (22) -----第五章 加载实体和导航属性之延迟加载

    翻译的初衷以及为什么选择<Entity Framework 6 Recipes>来学习,请看本系列开篇 第五章 加载实体和导航属性 实体框架提供了非常棒的建模环境,它允许开发人员可视化地使 ...

  9. python学习心得第五章

    python学习心得第五章 1.冒泡排序: 冒泡是一种基础的算法,通过这算法可以将一堆值进行有效的排列,可以是从大到小,可以从小到大,条件是任意给出的. 冒泡的原理: 将需要比较的数(n个)有序的两个 ...

随机推荐

  1. Centos7安装部署openstack--nova计算服务

    一.概述 使用OpenStack计算服务来托管和管理云计算系统.OpenStack计算服务是基础设施即服务(IaaS)系统的主要部分,模块主要由Python实现. OpenStack计算组件请求Ope ...

  2. 浅谈bfs

    广搜(bfs) 定义 广度优先算法,简称BFS.是一种图形搜索演算法,简单的说,BFS是从根节点开始,沿着树的宽度遍历树的节点,如果发现目标,终止. 与dfs的相似之处与不同 结合深搜理解 相同点:都 ...

  3. (私人收藏)2019WER积木教育机器人赛(普及赛)基础解决方案

    2019WER积木教育机器人赛(普及赛)基础解决方案 含地图.基础解决方案.全部路线的往返.详细规则.视频.搭建方案 EV3;乐高;机器人比赛;能力风暴;WER https://pan.baidu.c ...

  4. 洛谷 P4910 帕秋莉的手环

    题意 多组数据,给出一个环,要求不能有连续的\(1\),求出满足条件的方案数 \(1\le T \le 10, 1\le n \le 10^{18}\) 思路 20pts 暴力枚举(不会写 60pts ...

  5. 「期望」「洛谷P1297」单选错位

    题目 题目描述 gx和lc去参加noip初赛,其中有一种题型叫单项选择题,顾名思义,只有一个选项是正确答案.试卷上共有n道单选题,第i道单选题有ai个选项,这ai个选项编号是1,2,3,-,ai,每个 ...

  6. Java编程技术之浅析Java容器技术

    Java容器 集合是一种存储数据的容器,是Java开发中使用最频繁的对象类型之一. 或许提起Collection,都会第一时间意识到List和Set以及Map等相关关键词.因为这几乎是我们日常开发里接 ...

  7. [Mybatis]Mybatis常用操作

    Mybatis是目前国内比较流行的ORM框架,特点是可以写灵活的SQL语句,非常适合中小企业的面向数据库开发. 本文总结自己开发过程中常用的Mybatis操作. 一.插入操作 主键自增插入单条 < ...

  8. gitlab-ci部署实现持续集成(centos7)

    一.gitlab安装 1. 环境准备 // selinux和 firewall 关闭 $ setenforce 0 $ sed -i "/^SELINUX/s/enforcing/disab ...

  9. day78 作业

    目录 1 在作业.html的代码基础上,完成商品数量的加减,注意商品数量如果低于0个,则自动删除当前商品 2 在作业.html的代码基础仧,完成购物车总价格的计算 3 使用ajax获取北京天气,并把昨 ...

  10. es6新增特性总结

    定义 ES6是ECMA为JavaScript制定的第6个标准版本,标准委员会决定,标准在每年6月正式发布并作为当年的正式版本,接下来的时间里就在此版本的基础上进行改动,直到下一年6月草案就自然变成新一 ...