集合第一发Collection

来源:互联网 发布:java可以生成apk吗 编辑:程序博客网 时间:2024/04/29 07:26

一、Collection

它是一个抽象的接口,要用它的实现类来new对象,实现类如下:

它的主要方法有:


当集合中实现类是hashSet的时候,所加入元素的存储位置由hash值定,此时对象不写hash方法时用的是object的内存地址,所以每次new对象的时候,hash值可能变也可能不变。如果对象谢了hashCode方法,那么位置就定下来了。在集合中,我们一般用Iterator迭代器来枚举集合中的元素(集合的查询组件,如我们acm中用到的Scanner)。通过一个显示代码来理解Collection:

主类:

package cn.hncu.collectionDemo;import java.util.ArrayList;import java.util.Collection;import java.util.HashMap;import java.util.HashSet;import java.util.Iterator;import java.util.Set;public class collectionDemo {public static void main(String[] args) {//new对象@SuppressWarnings("rawtypes")//Collection collection=new ArrayList();Collection collection=new HashSet();//增collection.add(1);collection.add(2);collection.add(new Person("01", "Mike", 20));collection.add(new Person("02", "TOm", 21));//删collection.remove(1);//改1collection.remove(1);collection.add(100);//改2Object[] objs=collection.toArray();collection.clear();for (int i = 0; i < objs.length; i++) {if(objs[i].equals(2)){objs[i]=500;}collection.add(objs[i]);}//查 要用迭代器Iterator it=collection.iterator();while(it.hasNext()){System.out.println(it.next());}}}
Person类:

package cn.hncu.collectionDemo;public class Person {private String Sno;private String name;private int age;public Person(String sno, String name, int age) {super();Sno = sno;this.name = name;this.age = age;}public String getSno() {return Sno;}public void setSno(String sno) {Sno = sno;}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;}@Overridepublic String toString() {return "Person [Sno=" + Sno + ", name=" + name + ", age=" + age + "]";}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + ((Sno == null) ? 0 : Sno.hashCode());result = prime * result + age;result = prime * result + ((name == null) ? 0 : name.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Person other = (Person) obj;if (Sno == null) {if (other.Sno != null)return false;} else if (!Sno.equals(other.Sno))return false;if (age != other.age)return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;return true;}}



0 0