java中有好多集合:List,ArrayList,Vector,HashSetTreeSet,它们之间的区别,java集合的框架等等总是很模糊,称有时间总结下。一、Collection接口和Iterator接口1.Collection框架:collection接口主要定义了一些 ...
java中有好多集合:List,ArrayList,Vector,HashSetTreeSet,它们之间的区别,java集合的框架等等总是很模糊,称有时间总结下。
一、Collection接口和Iterator接口
1.Collection框架:
collection接口主要定义了一些操作集合元素的方法:
boolean
| add( E e) Ensures that this collection contains the specified element (optional operation).如果插入成功,返回true |
boolean
| addAll( Collection<? extends E> c) Adds all of the elements in the specified collection to this collection (optional operation).改变返回true |
void
| clear() Removes all of the elements from this collection (optional operation). |
boolean
| contains( Object o) Returns true if this collection contains the specified element. |
boolean
| containsAll( Collection<?> c) Returns true if this collection contains all of the elements in the specified collection. |
boolean
| equals( Object o) Compares the specified object with this collection for equality. |
int
| hashCode() Returns the hash code value for this collection. |
。。。。。。具体可看文档
2.使用Iterator接口遍历几何元素
Iterrator接口隐藏了各种Collection实现类的细节,向应用程序提供了遍历Collection集合元素的统一编程接口。Iterator接口里定义了如下三个方法:
Boolean hashNext(): 如果被迭代的集合元素还没有被遍历,则返回true.
Object next(): 返回集合里的下一个元素。
Void remove(): 删除集合里上一次next方法返回的元素。
**当使用Iterator迭代访问Collection集合元素时,Collection集合里的元素不能被改变,只有通过Iterator的remove方法删除上一次next方法返回的集合元素才可以;否则将引发java.util.Concurrent ModificationException异常。
下面开始一个个类介绍
二、set集合
Set集合的方法与Collection基本上完全一样,它没有提供额外的方法。实际上Set就是Collection,只是行为略有不同(Set不允许包含重复元素)。
Set判断两个对象是否相同是根据equals方法。也就是说,只要两个对象用equals方法方法比较返回false,Set就会接受这两个对象。
1.HashSet是Set的典型实现,HashSet按Hash算法来存储集合中的元素,因此具有很好的存取和查找性能。
特点:不能保证元素的排列顺序;不是同步的,不是线程安全;集合值可以是null。
HashSet集合判断两个元素的相等的标准是两个对象通过equals方法比较相等,并且两个对象的hashCode()方法返回值也相等。
示例:
import java.util.*;//类A的equals方法总是返回true,但没有重写其hashCode()方法class A{ public boolean equals(Object obj) { return true; }}//类B的hashCode()方法总是返回1,但没有重写其equals()方法class B{ public int hashCode() { return 1; }}//类C的hashCode()方法总是返回2,但没有重写其equals()方法class C{ public int hashCode() { return 2; } public boolean equals(Object obj) { return true; }}public class TestHashSet{ public static void main(String[] args) { HashSet books = new HashSet(); //分别向books集合中添加2个A对象,2个B对象,2个C对象 books.add(new A()); books.add(new A()); books.add(new B()); books.add(new B()); books.add(new C()); books.add(new C()); System.out.println(books); }}
海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com
原标题:Java集合概述
关键词:JAVA
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。