当前位置: 移动技术网 > IT编程>开发语言>Java > 14_集合

14_集合

2019年06月07日  | 移动技术网IT编程  | 我要评论

妮图网,冯巩小品下载,宁阳二手房

集合
为什么会出现集合框架
[1] 之前的数组作为容器时,不能自动拓容
[2] 数值在进行添加和删除操作时,需要开发者自己实现添加和删除。
 
 
collection接口
collection基础api
java集合框架提供了一套性能优良、使用方便的接口和类,它们位于java.util包中。
collection表示集合的根接口,可以看成一个容器,存储了很多对象,这些对象称为collection元素。collection要求元素必须是引用数据类型。
collection 根据其元素的特征可以分为
list接口->元素有序、可重复
set 接口-> 元素无序、不可重复
 
 
思考:collection提供了具备什么能力?=> 对容器增删改查
 
public class test01 {
public static void main(string[] args) {
/**
* 增:add/addall
* 删:clear/remove/removeall/retainall
* 改:
* 查:contains/constainsall/size/isempty
* 其他:equals
* 遍历:iterator()
*/
 
 
collection col1 = new arraylist();
col1.add("apple"); // object obj = "apple" 多态
col1.add("banana"); // integer i = 1; 装箱
// 注意:collection可以添加任意类型的数据,最好添加统一类型的数据方便未来统一访问。
 
collection col2= new arraylist();
col2.add("apple");
col2.add("banana");
// col1.addall(col2);
//system.out.println(col1);
 
 
//col1.clear(); // 清空集
//col1.remove("apple"); // 移除指定元
//col1.removeall(col2); // 移除指定集合中的多个元
//col1.retainall(col2); // 保留指定集合col2中的元素,其他删
//system.out.println(col1);
 
//col1.remove(1); // [apple, banana, 2]
//system.out.println(col1.contains("apple"));
//system.out.println(col1.containsall(col2));
//system.out.println(col1.size()); // 返回元素个
//system.out.println(col1.isempty());
 
boolean r = col1.equals(col2);
system.out.println(r);
 
}
}
 
遍历和iterable
iterable 表示可遍历的,具备遍历的能力。其定义了一个方法iterator用于返回集合上的迭代器,该迭代器用于foreach快速遍历。
 
public static void main(string[] args) {
 
collection col1 = new arraylist();
col1.add("apple");
col1.add("coco");
col1.add("banana");
 
// 遍历集合中的元素
/*
* object 表示迭代元素类
* item 表示迭代变
* */
// 快速遍历
for (object item : col1) {
system.out.println(item);
}
 
// 迭代器遍历
iterator it1 = col1.iterator(); // 返回集合的迭代器
while(it1.hasnext()) {
string item = (string)it1.next();
system.out.println(item);
}
 
// 写法(更节省内存)
for(iterator it2 = col1.iterator();it2.hasnext();) {
string item = (string)it2.next();
system.out.println(item);
}
}
 
 
list接口
list 接口称为有序的序列,提供了索引(index)对容器中的元素进行增、删、改、查。
index让list集合中的元素有序、可重复。
 
list接口常用方法
 
public static void main(string[] args) {
/**
* 增:add(index,e)/addall(index,c)/add(e)/addall(c)/
* 删:remove(index)/clear()/remove(e)/removeall(c)/retainall(c)
* 改:set(index,e);
* 查:get(index)/indexof(e)/lastindexof(e)/contains/constainsall/size/isempty
* 其他:equals
* 遍历:iterator() / listiterator()
*/
 
list list1 = new arraylist();
// 【1】添加
// 追加
list1.add("apple");
list1.add("banana");
// 在指定index位置添加元素coco
list1.add(0,"coco");
 
list list2 = new arraylist();
list2.add(1);
list2.add(2);
list1.addall(0, list2);
system.out.println(list1);
 
// 【2】移除
//list1.remove(0);
//system.out.println(list1);
 
// 【3】修改
list1.set(0, 100);
system.out.println(list1);
 
// 【4】查看元素 可能产生indexoutofboundsexception
// system.out.println(list1.get(6));
system.out.println(list1.indexof(200));
 
// list1.add(2);
// system.out.println(list1.lastindexof(2));
 
}
 
 
list接口遍历
list接口中提供了一个listiterator方法,返回列表的列表迭代器,属于listiterator接口,提供以任意方向(正向、逆向)遍历列表,同时在遍历列表的过程中还可以操作列表。
public static void main(string[] args) {
 
// list 集合的遍历
list list = new arraylist();
list.add("apple");
list.add("banana");
list.add("coco");
// 【1】 for 循环
for(int i=0;i<list.size();i++) {
string item = (string) list.get(i);
system.out.println(item);
}
 
// 【2】 快速遍历
for(object item:list) {
system.out.println(item);
}
 
// 【3】iterator
iterator it1 = list.iterator();
while(it1.hasnext()) {
system.out.println(it1.next());
}
 
// 【4】listiterator 获取列表的迭代器
listiterator it2 = list.listiterator();
// 正向遍历(a)
while(it2.hasnext()) {
system.out.println(it2.next());
}
// 逆向遍历(b)
while(it2.hasprevious()) {
system.out.println(it2.previous());
}
 
// 【5】从指定位置开始迭代(c)
system.out.println("--listiterator(index)--");
listiterator it3 = list.listiterator(1);
while(it3.hasnext()) {
system.out.println(it3.next());
}
}
 
思考:iterator和listiterator区别?
 
数据结构(补充知识)
线性表
根据物理空间是否连续,可以把线性表分为数组和链表。
 
数组:物理上连续、逻辑上也连续的内存空间,通过index来访问元素。
 
链表:物理上不连续、逻辑上连续的内存空间,也可以通过index来访问元素。
 
队列
队列是以一个方向先进先出的数据结构
栈是一种先进后出的数据结构
arraylist、 linkedlist、vector
arraylist
arraylist 类是list接口的实现类,底层数据结构是数组
arraylist 是数组的包装类,jdk1.2出现,提供了操作底层数据的很多方法,同时向arraylist中添加元素时,容器可以自动拓容。
arraylist 是线程不安全。
 
api和list接口一样。
vector
vector 类是list接口的实现类,底层数据结构也是数组。
vector是数组的包装类,jdk1.0出现,提供了操作底层数据的很多方法,同时向vector中添加元素时,容器可以自动拓容,也提供了自身特有的方法xxxelement等方法。 vector 是线程安全。
 
面试题:arraylist和vector有什么区别?
相同点:
[1] 都是list接口的实现类、底层数据结构都是数组
 
不同点
[1] arraylist jdk1.2;vector jdk1.0
[2] arraylist 线程不安全,效率高;vector 线程安全,效率低
[3] vector较arraylist拥有特有的方法。
 
linkedlist
linkedlist 是list接口的实现类,底层数据结构是链表。
linkedlist是链表的包装类,jdk1.2出现,提供了操作底层数据的很多方法,当向linkedlist中添加元素时,通过链入元素增加容量。
linkedlist线程不安全。
 
public class test01 {
public static void main(string[] args) {
list list1 = new linkedlist();
 
// 【1】添加
list1.add("apple");
list1.add("banana");
list1.add("coco");
system.out.println(list1);
 
// 【2】删除
list1.remove("apple");
 
// 【3】修改
list1.set(0, "banana x");
system.out.println(list1);
 
// 【4】查看
system.out.println(list1.get(0));
 
}
}
 
 
linkedlist也实现了栈、队列、双向队列接口。
以栈的方式访问linkedlist
public class test02 {
public static void main(string[] args) {
// 以栈形式访问
linkedlist stack1 = new linkedlist();
 
// 入栈
stack1.push("apple");
stack1.push("banana");
 
// 出栈
system.out.println(stack1.pop());
system.out.println(stack1.pop());
 
// 如果栈中没有元素,抛出nosuchelementexception
system.out.println(stack1.pop());
}
}
 
 
以队列(queue接口)的方式访问linkedlist
public static void main(string[] args) {
// 以队列形式访问
linkedlist queue = new linkedlist();
 
// 入队
/*
头(出口)<----------尾(入口)
---------------------
apple banana coco
---------------------
*/
//queue.add("apple");
//queue.add("banana");
//queue.add("coco");
//system.out.println(queue);
 
// 出队
//queue.remove();
//queue.remove();
//queue.remove();
// 抛出nosuchelementexception
//queue.remove();
//system.out.println(queue);
 
 
// 检测元素:获取但不移除此列表的头(第一个元素)
//system.out.println(queue.element());
//system.out.println(queue.element());
 
 
 
/*queue.offer("apple");
queue.offer("banana");
queue.offer("coco");*/
system.out.println(queue);
 
//queue.poll();
//system.out.println(queue);
//queue.poll();
//queue.poll();
// 如果队列为空,返回null
//string item = (string)queue.poll();
//system.out.println(item);
 
system.out.println(queue.peek());
}
 
以双向队列(deque接口)方式访问linkedlist
public static void main(string[] args) {
// 以双向队列形式访问
linkedlist queue = new linkedlist();
 
/*
*
头 尾
<-------------------
---------------------
apple banana coco
---------------------
------------------->
 
*/
 
queue.addfirst("apple");
queue.addlast("banana");
queue.addlast("coco");
 
//queue.removefirst();
//queue.removelast();
//queue.removelast();
 
// nosuchelementexception
//queue.removelast();
//system.out.println(queue);
system.out.println(queue.getfirst());
system.out.println(queue.getlast());
}
 
泛型(generic)
泛型概念(a)
泛型允许程序员在强类型程序设计语言中编写代码时定义一些可变部分。
那些可变部分在使用前必须作出指明。形式
arraylist<t> list = null;
表示声明了一个arraylist容器,容器中存储的数据类型是t类型,t类型此时就是泛型。
t表示一种数据类型,但现在还不确定。
 
泛型在使用时,一定要确定类型。
 
arraylist<string> list2 = new arraylist<string>();
表示声明了一个arraylist容器,容器中存储的数据类型是string类型。
 
泛型只在编译器起作用,运行时不知道泛型的存在。
 
泛型擦除(c)
public static void main(string[] args) {
arraylist<integer> list = new arraylist<integer>();
 
 
system.out.println(list instanceof arraylist);
system.out.println(list instanceof arraylist<?>);
system.out.println(list instanceof arraylist<integer>); //error
 
}
cannot perform instanceof check against parameterized type arraylist<integer>. use the form arraylist<?> instead since further generic type information will be erased at runtime
 
 
泛型就是程序设计过程中将类型参数化。
 
泛型类(a)
当一个类中的属性类型不确定时,此时可以把该属性声明为泛型。
public class student<t> {
private t t;
public t gett() {
return t;
}
public void sett(t t) {
this.t = t;
}
}
 
思考:请设计一个容器,提供增删改查的方法?
 
泛型方法(a)
当一个方法的形参参数类型不确定时,可以使用泛型。
public class student{
 
 
/*
public void add(int a,int b) {
system.out.println(a+b);
}
 
public void add(float a,float b) {
system.out.println(a+b);
}
 
public void add(char a,char b) {
system.out.println(a+b);
}
public void add(string a,string b) {
system.out.println(a+b);
}
*/
 
public <t> void add(t a,t b) {
system.out.println(a.tostring()+b.tostring());
}
}
 
泛型方法在一定程度上优化了方法重载,不能取代。
 
泛型的可变参数
// 方法的可变参数
/*public void add(int...args) {
// 方法的可变参数在方法调用时,以args数组形式存在于方法
system.out.println(arrays.tostring(args));
}*/
 
public <t> void add(t...args) {
system.out.println(arrays.tostring(args));
}
 
泛型的可变参数方法进一步优化了方法重载,不能完全取代。
 
泛型接口(c)
当泛型接口中的方法类型(返回值、形参)不太确定,可以使用泛型接口。
public interface myinterface<t> {
public void showinfo(t a);
}
 
实现类知道操作接口中方法的参数类型
public class implclass implements myinterface<string>{
@override
public void showinfo(string a) {
// todo auto-generated method stub
 
}
}
 
实现类不知道实现接口中方法的参数类型,实现类继续泛下去。
public class implclass2<t> implements myinterface<t>{
@override
public void showinfo(t a) {
// todo auto-generated method stub
 
}
}
 
泛型的上限和下限(c)
[1]泛型上限
public static void print(arraylist<? extends pet> list) {
for(pet pet:list) {
pet.showinfo();
}
}
<? extends a> 表示?必须a的子类,a作为上限已经确定。
arraylist<? extends a> list 表示声明了一个容器list,list中存储的元素必须是a的子类。
[2]泛型下限
<? super a> 表示?必须a的父类,a作为下限已经确定。
arraylist<? super a> list 表示声明了一个容器list,list中存储的元素必须是a的父类。
 
iterator和listiterator
读iterator实现类源码(hasnext、next)
 
public static void main(string[] args) {
 
arraylist<string> list = new arraylist<string>();
list.add("apple");
list.add("banana");
list.add("coco");
 
// 需求:在遍历的过程中,添加元素
iterator<string> it = list.iterator();
while(it.hasnext()) {
string item = it.next();
if(item.equals("banana")) {
// list.add("test");
}
}
system.out.println(list);
 
listiterator<string> it2 = list.listiterator();
while(it2.hasnext()) {
string item = it2.next();
if(item.equals("banana")) {
it2.add("test");
}
}
system.out.println(list);
}
exception in thread "main" java.util.concurrentmodificationexception
at java.util.arraylist$itr.checkforcomodification(arraylist.java:909)
at java.util.arraylist$itr.next(arraylist.java:859)
at cn.sxt06.iterator.test01.main(test01.java:18)
当遍历一个集合时,不能对集合进行添加操作,可能会出现并发修改异常。如果要对其进行添加操作,需要使用listiterator接口。
set接口
set接口表示的集合元素是无序、唯一的。
public static void main(string[] args) {
/**
* 增:add/addall
* 删:clear/remove/removeall/retainall
* 改:
* 查:contains/containsall/isempty/equals/size
* 遍历:iterator
*/
 
set<string> set = new hashset<string>();
// 【1】添加
boolean r;
r = set.add("apple");
system.out.println(r);
set.add("coco");
set.add("banana");
 
r = set.add("apple"); // 没有添加成功
system.out.println(r);
 
// 【2】删除
// set.clear();
set.remove("coco");
system.out.println(set);
}
 
set遍历
public static void main(string[] args) {
set<string> set = new hashset<string>();
set.add("apple");
set.add("coco");
set.add("banana");
 
// foreach
for(string str:set) {
system.out.println(str);
}
 
iterator<string> it = set.iterator();
while(it.hasnext()) {
system.out.println(it.next());
}
}
 
hashset
hashset是set接口的实现类,底层数据结构是哈希表。
hashset 线程不安全。
 
hashset的工作原理
hashset底层数据结构是哈希表/散列表
 
hashset存储元素时
[1] 求元素的hash码
[2] equals比较集合是否存在相同元素。
 
思考:如何把自定义对象存入hashset中?
package cn.sxt02.hashset;
public class student {
 
private string id;
private string name;
private int age;
// …
 
@override
public int hashcode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((id == null) ? 0 : id.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 != other.age)
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@override
public string tostring() {
return "student [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
 
总结:
[1]存入hashset中的元素必须实现hashcode和equals方法
[2]元素的hashcode一样,经过y=k(x)散列出来的位置一定一样。元素的hashcode不一样,经过y=k(x)散列出来的位置有可能一样。
[3] 散列函数多半是 hashcode % 空间长度。为什么?
 
linkedhashset
linkedhashset 是set接口的实现类,底层数据结构是哈希表+链表,其中链表应用维持添加次序。
 
画linkedhashset工作原理图?
 
treeset
treeset 是set接口的实现类,底层数据结构是二叉树,按照自然升序存储。
treeset实现线程不安全的。
 
treeset工作原理
treeset<integer> set = new treeset<integer>();
set.add(2);
set.add(3);
set.add(1);
set.add(4);
set.add(3);
system.out.println(set);
 
当向treeset存入一个元素时,
[1]把待添加的元素t和根节点比较,如果t小于根节点,t存入左子树;如果t大于根节点,t存入右子树
[2]一旦确定子树后,t元素要和子树根节点比较,重复[1]步骤,如果需要相等,丢弃t。
 
 
 
 
需求: 把自定义对象按年龄存入treeset中?
 
把自定义对象存入treeset中一定要提供比较策略,否则会出现classcastexception异常。
 
比较策略分为两种,一种是内部比较器,一种是外部比较器。
内部比较器
内部比较器就是实现comparable接口
package cn.sxt04.treeset;
public class student implements comparable<student>{
 
private string id;
private string name;
private int age;
// . . .
@override
public int compareto(student o) {
// 按照年龄比较
if(this.getage() < o.getage()) {
return -1;
}else if(this.getage() == o.getage()) {
return 0;
}else {
return 1;
}
}
}
 
思考:把自定义对象按年龄升序存入treeset中,如果年龄一样,再按照名字自然升序。
@override
public int compareto(student o) {
 
// return this.getage() - o.getage();
 
// 按照年龄比较
if(this.getage() < o.getage()) {
return -1;
}else if(this.getage() == o.getage()) {
 
/*if(this.getname().compareto(o.getname()) < 0) {
return -1;
}else if(this.getname().compareto(o.getname()) == 0) {
return 0;
}else {
return 1;
}*/
 
return this.getname().compareto(o.getname());
 
}else {
return 1;
}
}
 
外部比较器
当开发者不知道添加元素类的源代码时,此时可以使用外部比较策略。外部比较器就是compartor接口。
 
public class test04 {
public static void main(string[] args) {
lencompare lencompare = new lencompare();
treeset<string> set = new treeset<string>(lencompare);
set.add("alex");
set.add("ben");
set.add("cocos");
set.add("scott");
// 需求:按照字符串的长度升序?
system.out.println(set);
}
}
class lencompare implements comparator<string> {
@override
public int compare(string o1, string o2) {
// [1] 按名称长度升序
// system.out.println("o1:"+o1);
// system.out.println("o2:"+o2);
// return o1.length() - o2.length();
// [2] 先按照名称长度,如果相等,按名称自然顺序
/*if (o1.length() == o2.length()) {
return o1.compareto(o2);
}
return o1.length() - o2.length();*/
 
 
// [3]按照长度降序
return o2.length() - o1.length();
}
}
package cn.sxt04.treeset;
import java.util.comparator;
import java.util.treeset;
public class test05 {
public static void main(string[] args) {
lencompare lencompare = new lencompare();
 
treeset<string> set = new treeset<string>(new comparator<string>() {
@override
public int compare(string o1, string o2) {
return o1.length() - o2.length();
}
});
 
set.add("alex");
set.add("ben");
set.add("cocos");
set.add("scott");
// 需求:按照字符串的长度升序
system.out.println(set);
}
}
map接口
map 是存储键值对(key-value)的接口。一个键值对被看出一个元素(entry)
一般而言,我们可通过key操作value。
 
 
map 常用方法
package cn.sxt05.map;
import java.util.arraylist;
import java.util.hashmap;
import java.util.list;
import java.util.map;
public class test01 {
public static void main(string[] args) {
/**
* 增:put/putall
* 删:clear/remove
* 改:put
* 查:get/containskey/containsvalue/isempty/size/values
* 遍历:entryset/keyset
*/
 
map<string, arraylist<string>> map = new hashmap<string,arraylist<string>>();
 
// 【1】添加
arraylist<string> list1 = new arraylist<string>();
list1.add("alex");
list1.add("alice");
list1.add("allen");
map.put("a", list1);
 
arraylist<string> list2 = new arraylist<string>();
list2.add("ben");
list2.add("bill");
map.put("b", list2);
 
arraylist<string> list3 = new arraylist<string>();
list3.add("coco");
list3.add("cill");
map.put("c",list3);
 
system.out.println(map);
 
// 【2】删除
// map.clear();
// map.remove("c");
// system.out.println(map);
 
// 【3】修改
arraylist<string> list4 = new arraylist<string>();
list4.add("doco");
list4.add("dill");
// 更新
map.put("c",list4);
system.out.println(map);
 
// 【4】获取
arraylist<string> list = map.get("c");
system.out.println(list);
 
// 其他
// system.out.println(map.containskey("c"));
arraylist<string> list5 = new arraylist<string>();
list5.add("doco");
list5.add("dill");
system.out.println(map.containsvalue(list5));
system.out.println(map.size());
 
// 获取所有的value到一个collection中
system.out.println(map.values());
}
}
 
map 遍历
package cn.sxt05.map;
import java.util.arraylist;
import java.util.hashmap;
import java.util.iterator;
import java.util.list;
import java.util.map;
import java.util.map.entry;
import java.util.set;
public class test02 {
public static void main(string[] args) {
/**
* 遍历:entryset/keyset
*/
map<string, string> map = new hashmap<string, string>();
map.put("b", "banana");
map.put("c", "coco");
map.put("a", "apple");
// map是无序的。如果想要map有序,选择key是一定要具有可排序性。一般建议用string作为key
// 【1】获取所有的key
set<string> keyset = map.keyset();
iterator<string> it = keyset.iterator();
while (it.hasnext()) {
string key = it.next();
system.out.println(key + "=>" + map.get(key));
}
 
// 快速遍历forearch???
 
 
// 【2】获取所有的entry
set<entry<string, string>> entryset = map.entryset();
iterator<entry<string, string>> it2 = entryset.iterator();
while(it2.hasnext()) {
entry<string, string> entry = it2.next();
system.out.println(entry.getkey()+"=>"+entry.getvalue());
}
 
// 快速遍历forearch???
 
system.out.println(map);
}
}
 
hashmap
hashmap是map接口的实现类,底层数据结构key是哈希表
hashmap 线程不安全,如果需要线程安全,请使用hashtable。
public class test01 {
public static void main(string[] args) {
 
hashmap<student, string> map = new hashmap<student,string>();
 
student s1 = new student("001", "大狗", 20);
student s2 = new student("002", "2狗", 21);
student s3 = new student("003", "3狗", 22);
 
student s4 = new student("002", "2狗", 21);
 
map.put(s1, "apple");
map.put(s2, "banana");
map.put(s3, "coco");
 
map.put(s4, "bill");
system.out.println(map);
 
}
}
 
如果用自定义对象作为key,一定要重写hashcode和equals方法用于key的判断。
 
linkedhashmap
linkedhashmap是map接口的实现类,底层数据结构key是哈希表+链表,链表用于维持添加次序。
linkedhashmap线程不安全。
package cn.sxt07.linkedhashmap;
import java.util.linkedhashmap;
public class test01 {
public static void main(string[] args) {
 
linkedhashmap<student, string> map = new linkedhashmap<student,string>();
 
student s1 = new student("001", "大狗", 20);
student s2 = new student("002", "2狗", 21);
student s3 = new student("003", "3狗", 22);
 
student s4 = new student("002", "2狗", 21);
 
map.put(s3, "coco");
map.put(s1, "apple");
map.put(s2, "banana");
 
map.put(s4, "bill");
 
system.out.println(map);
 
}
}
 
treemap
treemap是map接口的实现类,底层数据结构key是二叉树。
treemap 线程不安全
package cn.sxt08.treemap;
import java.util.treemap;
public class test02 {
public static void main(string[] args) {
 
 
treemap<student, string> map = new treemap<student,string>();
 
student s1 = new student("001", "大狗", 20);
student s2 = new student("002", "2狗", 21);
student s3 = new student("003", "3狗", 22);
 
student s4 = new student("002", "4狗", 21);
 
map.put(s3, "coco");
map.put(s1, "apple");
map.put(s2, "banana");
 
map.put(s4, "bill");
 
system.out.println(map);
 
}
}
注意:比较时,只看比较策略,如果比较策略相同,就更新value,不更新key。
 
总结

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网