集合类:
Collection接口:
*一个独立的元素的序列(单列,即一个位置放一个元素)
*Collection接口下主要分为List集合和Set集合
*List集合的特点是元素有序(先进先出)、允许有重复元素
*Set集合的特点是元素无序(没有先后顺序)、不允许有重复元素
Map接口:
*一组成对的“键值对”对象,允许根据键来查找值
*Map集合的键值不允许有重复(因为是根据键来查找值的),所以Map的所有键构成了一个Set集合
Iterator接口:
*JDK1.5新定义的接口作为Collection的付接口
*主要为了实现增强for循环
List集合(特点)
ArrayList:
*底层数组实现
*查找快,增删慢(原因是这个集合是有序的,删除一个元素的时候,后一个元素需要往前挪动一个位置,增加的时候需要往后挪动一个位置)
*线程不安全(线程不同步)
Vector:
*与ArrayLis基本一样
*线程安全(线程同步)
LinkedList:
*底层链表实现
*增删快,查找慢
*线程不安全
集合元素的存取:
*List集合元素存取方法一致
*使用add()方法增加元素
*由于List集合有序,可以使用get(int i)方法获取元素
*元素的迭代(Iterator)
1.通过集合对象的iterator()方法获得迭代器Iterator
2.通过Iterator迭代器的hasNext()方法判断是否存在下一个元素
3.通过Iterator迭代器的next()方法获取下一个元素
*元素的迭代(Enumeration)
1.迭代Vector集合中的元素可以使用Enumeration(也只有Vector集合才有这种迭代方式)
2.通过Enumeration的hasNextElements()方法判断是否还有元素
3.通过Enumeration的nextElement()方法返回下一个元素
遍历Collection集合分支下,List集合的实现类所有方法如下所示:
Vector<String> al = new Vector<String>();
al.add("xxc");
al.add("pkq");
al.add("xxm");
//1.使用枚举遍历Vector集合(只有Vector集合有)
Enumeration<String> e = al.elements();
while(e.hasMoreElements()){
System.out.println("枚举----->"+e.nextElement());
}
//2.使用Iterator的while循环结构遍历集合
Iterator<String> t = al.iterator();
while(t.hasNext()){
System.out.println("while循环---->"+t.next());
}
//3.使用Iterator的for循环结构遍历集合
for(Iterator<String> t1 = al.iterator();t1.hasNext();){
System.out.println("for循环----->"+t1.next());
}
//4.使用增强for循环遍历 如果前面没有指定泛型则String的位置需要写Object
for(String s : al){
System.out.println("增强for循环----->"+s);
}
//5.使用一般for循环遍历数组
for(int i=0;i<al.size();i++){
System.out.println("使用一般for循环------>"+al.get(i));
}
可变参数:
public class Test {
public static void main(String[] args) {
run("1","2");
}
static void run(String s1,String s2){
System.out.println("固定参数调用");//这个方法调用
}
static void run(String s1,String...str){
System.out.println("可变参数调用");
}
}
当固定参数和可变参数方法都满足要求时,优先固定参数
public class Test {
public static void main(String[] args) {
run("1","2");//这时候这个run方法是没法正确执行的,因为以下两个方法都满足
}
static void run(String s1,String...str){
System.out.println("可变参数调用");
}
static void run(String s1,String s2,String...str){
System.out.println("可变参数调用");
}
}
当两个可变参数的方法都满足要求时,无法执行
注意:可变参数必须是参数列表中最后一个参数。
例如:去除ArrayList中的重复元素,元素是对象类型
方法一:建立一个新的ArrayList集合,遍历需要被去重的集合,用contains判断,如果新的集合中不包含此元素,则往新的集合中增加此元素,反之不增加。最后,得到的新集合中的元素都是没有重复的。
(注意:因为对象去重复元素,而contains底层用的还是equals,所以我们要在比较的对象中覆写equals方法)
Person类(覆写了equals方法)
public class Person {
private String name;
private int age;
public Person(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 boolean equals(Object obj){
if(this == obj){
return true;
}
if(obj instanceof Person){
Person p = (Person)obj;
if(this.name.endsWith(p.name) && this.age == p.age){
return true;
}
}
return false;
}
}
测试类
public class ArrayListTest {
public static void main(String[] args) {
ArrayList<Person> a = new ArrayList<Person>();
a.add(new Person("xxc1",10));
a.add(new Person("xxc2",20));
a.add(new Person("xxc1",10));
a = getSingleElement(a);
System.out.println(a.size());//打印2
for(Person p : a){
System.out.println(p.getName());
}
}
private static ArrayList<Person> getSingleElement(ArrayList<Person> a) {
ArrayList<Person> al = new ArrayList<Person>();
Iterator<Person> i = a.iterator();
while(i.hasNext()){
Person p = (Person)i.next();
if(!al.contains(p)){
al.add(p);
}
}
return al;
}
}
方法二:因为HashSet集合是不能存在重复元素的,那我们可以遍历ArrayList集合,将每一个元素往HashSet中存,这样就能去掉重复元素。当然,千万别忘记要在对象里覆写HashCode()和equals()。
Person类(覆写了equals方法和hashCode方法)
public class Person {
private String name;
private int age;
public Person(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 boolean equals(Object obj){
if(this == obj){
return true;
}
if(obj instanceof Person){
Person p = (Person)obj;
if(this.name.endsWith(p.name) && this.age == p.age){
return true;
}
}
return false;
}
@Override
public int hashCode(){
return this.name.hashCode()*31+age;
}
}
测试类
public class ArrayListTest {
public static void main(String[] args) {
ArrayList<Person> a = new ArrayList<Person>();
a.add(new Person("xxc1",10));
a.add(new Person("xxc2",20));
a.add(new Person("xxc1",10));
HashSet<Person> hs = getSingleElement(a);
for(Person p : hs){
System.out.println(p.getName());
}
}
private static HashSet<Person> getSingleElement(ArrayList<Person> a) {
HashSet<Person> hs = new HashSet<Person>();
for(Person p : a){
hs.add(p);
}
return hs;
}
}
证明remove方法在删除元素时,是用equals方法来进行判断相同元素的。
public class ArrayListTest {
public static void main(String[] args) {
ArrayList<Person> a = new ArrayList<Person>();
a.add(new Person("xxc1",10));
a.add(new Person("xxc2",20));
a.add(new Person("xxc1",10));
a.remove(new Person("xxc1",20));
for(Person p : a){
System.out.println(p.getName());
}
}
}
删除以后剩下 第二个和第三个元素。从以上例子可以看出,虽然remove方法里是新new了一个Person对象,但是还是能删除,就证明了比较的不是引用的内存地址值,而是equals比较了各个属性。
Set集合(特点)
Set集合通过存入对象的equals方法来保证集合中没有重复元素
HashSet:
*线程不同步的
*HashSet是Set的子类,因此也没有重复元素
*底层使用哈希算法保证没有重复元素
*存储对象时,先调用对象的HashCode()方法,找到存储位置,再和当前存储上已经存在的元素通过equals方法进行比较吗如果返回false,才能进行存储
*往HashSet集合里存储的对象必须正确重写hashCode和equals方法,如果没有重写,那么就算是两个对象的属性值都相同,他们的hashCode也是不相同的,从而被认为是两个不同的对象存入到HashSet中
*如果只是String类型和Integer类型的,则不需要覆写这两个方法也能进行重复元素的去除。
注意:在重写HashCode的时候让属性乘以31,可以更好的防止重复检验
Person类(重写了equals和HashCode方法)
public class Person {
String name;
int age;
public Person(String name,int age){
this.name = name;
this.age = age;
}
public boolean equals(Object obj){//重写equals方法
if(obj == this){
return true;
}
if(obj instanceof Person){
Person p = (Person)obj;
if(this.name.equals(p.name) && this.age == p.age){
return true;
}
}
return false;
}
public int hashCode(){//重写hashCode方法
return name.hashCode()*31+age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
public class HashSetTest {
public static void main(String[] args) {
HashSet<Person> hs = new HashSet<Person>();
hs.add(new Person("xxc1",10));
hs.add(new Person("xxc2",20));
hs.add(new Person("xxc3",30));
hs.add(new Person("xxc1",10));
hs.add(new Person("xxc4",40));
for(Person p : hs){
System.out.println(p);
}
}
}
LinkedHashSet:
*线程不同步
*这个集合和HashSet唯一不同的是,此集合类型是有序的,也就是先进先出。而且也是去重复元素的。
HashSet<String> lhs = new LinkedHashSet<String>();
lhs.add("22");
lhs.add("dd");
lhs.add("zz");
for(String str : lhs){
System.out.println(str);
}
输出顺序还是22 dd zz。先进先出,有序。
TreeSet:
*线程不同步
*可以对Set集合中的元素进行排序。
*TreeSet判断元素唯一性的方式:根据比较方法的返回值是否为0,如果为0,叫表示两个对象是相同元素,则不往TreeSet集合中存。
*TreeSet存入两个以上的对象元素,要么此对象必须实现Comparable接口,覆写compareTo方法,要么TreeSet在创建的时候就带有比较器。注意:比较器在自定义类中定义不灵活,因为自定义类可能不是我们定义的,而是别人定义的,此时我们又不能再改变这个自定义类。
*如果希望元素有序地输出(先进先出)那么可以将对象类中的compareTo或比较器中的comparator的返回值定义为1,先进后出的话就返回-1。
利用TreeSet集合进行排序
方法一:在对象中实现Comparable接口,覆写compareTo方法。让元素自身带有排序功能。
Person对象类
public class Person implements Comparable{//实现接口
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person [name=" + name + ", 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;
}
public int compareTo(Object o){//覆写接口中的放
Person p = null;
if(o instanceof Person){
p = (Person)o;
}
/*if(this.age > p.age){
return 1;
}
if(this.age < p.age){
return -1;
}
if(this.age == p.age){
int temp = this.name.compareTo(p.name);
if(temp > 0){
return 1;
}else if(temp < 0){
return -1;
}
return 0;
}
return 0;//写这个只是为了编译通过
*/
//上面这一片被注释的代码的功能,可以用下面两句话就能完成功能
int temp = this.age - p.age;//由于age肯定是正整数,所以不怕有小数,可以直接相减后比大小
return temp ==0?this.name.compareTo(p.name):temp;
}
}
测试类
public class TreeSetTest {
public static void main(String[] args) {
TreeSet<Person> ts = new TreeSet<Person>();
ts.add(new Person("xxc1",40));
ts.add(new Person("xxc2",20));
ts.add(new Person("xxc3",30));
ts.add(new Person("xxc4",30));
ts.add(new Person("xxc0",20));
for(Person p : ts){
System.out.println(p);
}
}
}
方法二:在TreeSet构造的时候就传入一个比较器,这个比较器需要实现Comparator接口,覆写compare方法。让集合具有比较功能。
注意:当对象类中具有比较规则,定义TreeSet时又传入了比较器,最后以比较器为准。
定义比较器,实现Comparator接口,覆写compare方法
public class ComparatorByName implements Comparator{
public int compare(Object o1, Object o2) {
Person p1 = null;
Person p2 = null;
if(o1 instanceof Person){
p1 = (Person)o1;
}
if(o2 instanceof Person){
p2 = (Person)o2;
}
int temp = p1.getName().compareTo(p2.getName());
return temp==0?p1.getAge()-p2.getAge():temp;
}
}
测试类
public class TreeSetTest {
public static void main(String[] args) {
TreeSet<Person> ts = new TreeSet<Person>(new ComparatorByName());
ts.add(new Person("xxc1",40));
ts.add(new Person("xxc2",20));
ts.add(new Person("xxc3",30));
ts.add(new Person("xxc4",30));
ts.add(new Person("xxc0",20));
for(Person p : ts){
System.out.println(p);
}
}
}
Map集合(特点)
Map集合(双列集合)一次添加一对元素。Collection(单列集合)一次添加一个元素
Map集合中必须保证键的唯一性。
添加方法:value put(key,value) 返回前一个和key关联的值,如果没有则返回null.
HashMap<Integer,String> hm = new HashMap<Integer,String>();
System.out.println(hm.put(1, "xxc1"));//打印null
System.out.println(hm.put(1, "xxc2"));//打印xxc1
删除方法:
*void clear():清空map集合
HashMap<Integer,String> hm = new HashMap<Integer,String>();
hm.put(1, "xxc1");
hm.put(2, "xxc2");
hm.clear();
System.out.println(hm);//是一个空集合{}
*value remove(key):根据指定的key删除这个键值对
HashMap<Integer,String> hm = new HashMap<Integer,String>();
hm.put(1, "xxc1");
hm.put(2, "xxc2");
hm.remove(2);
System.out.println(hm);//打印{1=xxc1}
判断方法:判断集合中是否包含某个键
HashMap<Integer,String> hm = new HashMap<Integer,String>();
hm.put(1, "xxc1");
hm.put(2, "xxc2");
System.out.println(hm.containsKey(1));//返回true
获取方法:根据某个键,获取value。如果键不存在,则返回null。
HashMap<Integer,String> hm = new HashMap<Integer,String>();
hm.put(1, "xxc1");
hm.put(2, "xxc2");
System.out.println(hm.get(1));
HashMap:
*允许空值空键
*线程是不同步的
*内部结构是哈希表
*HashMap是不允许有重复键的,如果是自定义对象去重复元素,那么去重的方法和HashSet是一样的,在对象类定义的时候覆写HashCode和Equals方法
和HashSet一样,HashMap也有一个LinkedHashMap子类,可以实现有序。即先进先出。
HashTable:
*不允许空值空键
*线程是同步的
*内部结构是哈希表
*已经被HashMap替代
TreeMap:
*线程不同步
*通过二叉树算法保证键唯一性
*可以进行排序,排序的方式和在TreeSet中一样,要不就是在自定义对象中实现Comparable接口,覆写compareTo(Object o)
要不就是在TreeMap创建的时候传入一个实现了Comparator接口并覆写compare方法的实现类
至于TreeMap是怎么去自定义类的重复元素的,其实他并不是靠覆写hashCode和equals来实现的,而是靠比较两个对象后返回的整数大于0等于0小于0来判断的。
HashMap中存入自定义对象,并去掉自定义类的重复值。
public class Person {
private String name;
private int age;
public Person(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;
}
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
@Override
public int hashCode(){//和HashSet一样需要覆写
return this.name.hashCode()*31+age;
}
@Override
public boolean equals(Object obj){//和HashSet一样需要覆写
Person p = null;
if(obj instanceof Person){
p = (Person)obj;
}
return this.name.equals(p.name) && this.age == p.age;
}
}
测试类
public class HashMapTest {
public static void main(String[] args) {
HashMap<Person,String> hs = new HashMap<Person,String>();
hs.put(new Person("xxc1",10),"火星");
hs.put(new Person("xxc2",20),"北京");
hs.put(new Person("xxc3",30),"上海");
hs.put(new Person("xxc3",30),"上海");
Iterator<Map.Entry<Person,String>> i = hs.entrySet().iterator();
while(i.hasNext()){
Map.Entry<Person, String> me = i.next();
Person p = me.getKey();
String value = me.getValue();
System.out.println(p.getName()+"-----"+p.getAge()+"---老家-->"+value);
}
}
}
TreeSet进行自定义元素的排序
Person类
public class Person implements Comparable<Person>{//继承接口
private String name;
private int age;
public Person(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;
}
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
public int compareTo(Person o) {//覆写方法,定义在元素中的就一个参数的,因为是拿外面的元素和自身比
Person p = null;
if(o instanceof Person){
p = (Person)o;
}
int temp = this.age-p.age;
return temp==0?this.name.compareTo(p.name):temp;
}
}
测试类
public class TreeMapTest {
public static void main(String[] args) {
TreeMap<Person,String> tm = new TreeMap<Person,String>(new Comparator<Person>() {//在TreeMap创建的时候就传入一个比较器。两个参数的。
public int compare(Person p1, Person p2) {
int temp = p1.getName().compareTo(p2.getName());
return temp==0?p1.getAge()-p2.getAge():temp;
}
});
tm.put(new Person("xxc4",10),"杭州");
tm.put(new Person("xxc2",20),"北京");
tm.put(new Person("xxc2",20),"北京");
tm.put(new Person("xxc3",30),"上海");
Set<Person> s = tm.keySet();
Iterator<Person> i = s.iterator();
while(i.hasNext()){
Person p = i.next();
String value = tm.get(p);
System.out.println(p.getName()+"------------"+p.getAge()+"------------"+value);
}
}
}
Collections工具类(用于集合)
这个类中的方法都是静态的
1.将集合反转
reverseOrder():返回一个比较器,它强行逆转实现了Comparable 接口的对象 collection 的自然顺序。
reverseOrder(Comparator<T> cmp):返回一个比较器,它强行逆转指定比较器的顺序。(这个方法可以反转已经有比较器的Tree集合)
public class CollectionsTets {
public static void main(String[] args) {
TreeSet<String> ts = new TreeSet<String>(Collections.reverseOrder(new LengthComparator()));//反转已有的比较器规则
ts.add("w");
ts.add("azweewew");
ts.add("abreew");
ts.add("cads");
System.out.println(ts);
}
}
class LengthComparator implements Comparator<String>{//根据字符串长度进行从短到长的排序
public int compare(String o1, String o2) {
return o1.length()-o2.length();
}
}
2.将集合中的指定元素全部替换成另一个元素
replaceAll(List<T> list, T oldVal, T newVal):使用另一个值替换列表中出现的所有某一指定值。
public class CollectionsTets {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("w");
al.add("aa");
al.add("azweewew");
al.add("abreew");
al.add("cads");
al.add("aa");
System.out.println(al);
Collections.replaceAll(al, "aa", "xxc");//将list集合中的aa全部替换成xxc set(indexOf("aa"),"xxc");一样,就是将这两步封装成一个方法了
System.out.println(al);
}
}
2.将集合中的所有元素全部替换成另一个元素
fill(List<? super T> list, T obj):使用指定元素替换指定列表中的所有元素。
public class CollectionsTets {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("w");
al.add("aa");
al.add("azweewew");
al.add("abreew");
al.add("cads");
al.add("aa");
System.out.println(al);
Collections.fill(al, "ss");
System.out.println(al);
}
}
3.将集合里的元素随机存放不同位置
shuffle(List<?> list)
:使用默认随机源对指定列表进行置换。
public class CollectionsTets {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList<String>();
al.add("w");
al.add("aa");
al.add("azweewew");
al.add("abreew");
al.add("cads");
al.add("aa");
System.out.println(al);
Collections.shuffle(al);//将list元素的集合随机存放,假如做扑克牌洗牌操作就会用到
System.out.println(al);
}
}
4.将枚举类型集合转换为ArrayList类型集合
list(Enumeration<T> e):返回一个数组列表,它按返回顺序包含指定枚举返回的元素。
public class CollectionsTets {
public static void main(String[] args) {
Vector<String> v = new Vector<String>();
v.add("xa");
v.add("xqwa");
v.add("sddsxa");
Enumeration<String> e = v.elements();
ArrayList<String> al = Collections.list(e);
System.out.println(al);
}
}
5.可以将线程不同步的集合变成线程同步
static
| synchronizedCollection(Collection<T> c) 返回指定 collection 支持的同步(线程安全的)collection。 | |
static
| synchronizedList(List<T> list) 返回指定列表支持的同步(线程安全的)列表。 | |
static
| synchronizedMap(Map<K,V> m) 返回由指定映射支持的同步(线程安全的)映射。 | |
static
| synchronizedSet(Set<T> s) 返回指定 set 支持的同步(线程安全的)set。 |
4.将集合转换成数组(为了是集合里的元素转换成数组后不能增删操作)
Object[] | toArray() 返回包含此 collection 中所有元素的数组。 | |
| toArray(T[] a) 返回包含此 collection 中所有元素的数组;返回数组的运行时类型与指定数组的运行时类型相同。 |
当使用第二种方法时,参数的数组长度该如何定义呢?
1.如果长度小于集合的size,那么该方法会创建一个同类型并且和集合size相同length的数组。
2.如果长度大于集合的size,那么该方法就会使用指定的数组,存储集合中的元素,多余位置默认为null。
所以建议数组长度为需要被转换的集合的size。
public class ToStringTest {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("xx1");
list.add("xx2");
list.add("xx3");
String[] arr = list.toArray(new String[list.size()]);
System.out.println(Arrays.toString(arr));
}
}
Arrays工具类(用于数组)
1.将数组打印出元素内容,而不是哈希值。
public class ToStringTest {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
System.out.println(Arrays.toString(arr));
}
}
2.将数组转换成list集合(为了使用集合中有的而数组中没的方法)
static
| asList(T... a) 返回一个受指定数组支持的固定大小的列表。 |
public class ToStringTest {
public static void main(String[] args) {
String[] arr = {"1","2","3","4","5"};
List<String> list1 = Arrays.asList(arr);
list1.add("xxc");//java.lang.UnsupportedOperationException 执行到这句话会出异常
}
}
出异常的原因是:经分析java源代码Arrys.asList();方法返回的不是平常熟悉的java.util.ArrayList类的对象。而是Arrays类的内部类的对象,而Arrays类里的内部类ArrayList没有实现AbstractList类的add方法,导致抛此异常!
如果一定要将一个数组转换成一个集合,并且想往集合里添加或删除元素的话,可以用以下方法解决:
public class ToStringTest {
public static void main(String[] args) {
String[] arr = {"1","2","3","4","5"};
List<String> list2 = new ArrayList<String>(Arrays.asList(arr));//new一个新的集合,并且在构造的时候就传入一个集合(数组转换后的集合)
list2.add("xxx");
System.out.println(list2);
}
}
注意:如果数组中的元素是对象,那么转成集合时,直接将数组中的元素作为集合中的元素进行集合存储。
如果数组中的元素是基本类型数值,那么会将该数组作为集合中的元素进行存储。
public class ToStringTest {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
List<int[]> list2 = Arrays.asList(arr);//因为被转换的数组的元素是基本数据类型,所以转换成的集合里的类型是数组类型
System.out.println(list2);
}
}