1.存储对象可以考虑 ①数组 ②集合
2.数组存储对象的特点的弊端 ①一旦创建其长度不可变 ②真实的存放数组的个数是不可知的
3.集合类:Java中的集合类主要由Map接口和Collection接口派生而来。其中Collection接口有两个常用的子接口,既List接口
和Set接口。所以经常说Java集合框架有三大类接口构成(Map接口、List接口和Set接口)
以下将简单介绍Collection接口常用的方法:
/**
* 集合的常用方法
*/
@Test
public void testCollection1() {
Collection coll = new ArrayList();
//1.size() 返回集合中元素的个数
System.out.println(coll.size());//0
//2.add(Object obj) 向集合中添加一个元素 ,默认是从集合的末尾添加
coll.add(123);
coll.add("黄渤");
coll.add(new Date());
coll.add(true);
System.out.println(coll.size());//4
//3.addAll(Collection coll) 将形参coll中包含的所有元素添加到集合中
Collection coll1 = Arrays.asList(1,2,3,4);
coll.addAll(coll1);
System.out.println(coll.size());//8
//4.isEmpty() 判断当前集合是否为空
System.out.println(coll.isEmpty());//false
//5.clear() 清空当前集合
coll.clear();
System.out.println(coll.isEmpty());//true
}
@Test
public void testCollection2() {
Collection coll = new ArrayList();
coll.add(123);
coll.add(new String("刘德华"));
coll.add(new Date());
coll.add(new Person("MM", 18));//添加一个匿名Person对象
//6.contains(Object obj)判断集合中是否包含obj元素,包含则返回true,反之,返回false
//★此方法判断的依据是根据元素所在的类的equals()方法来进行判断的
//如果元素存入的是自定义类的对象,要求:自定义类中重写equals()方法!!!
boolean b1 = coll.contains(new String("刘德华"));
//如果Person类中没有重写equals()方法的话,此处的b1就是false:重写,则为true
b1 = coll.contains(new Person("MM", 18));
System.out.println(coll);
System.out.println(b1);
//7.containsAll(Collection coll)判断当前集合中是否包含coll中的所有元素
Collection co = new ArrayList();
co.add(123);
co.add("刘德华");
co.add(456);
boolean b3 = coll.containsAll(co);
/*NumberFormat f = NumberFormat.getCurrencyInstance();
System.out.println(f.format(123.6));*/
System.out.println("#"+b3);
//8.retainAll(Collection coll)求当前集合与coll共有的元素,并返回给当前集合
coll.retainAll(co);
System.out.println(coll);//123, 刘德华
//9.remove(Object obj)删除集合中的obj元素,若删除成功返回true,反之返回false
boolean b4 = coll.remove("BB");
System.out.println(b4);//false
}
@Test
public void testCollection3() {
Collection coll = new ArrayList();
coll.add(123);
coll.add("范冰冰");
coll.add(new Date());
// coll.add(new Person());
Collection co = new ArrayList();
co.add(123);
co.add("范冰冰");
//10.removeAll(Collection coll) 从当前集合中删除包含coll的元素
// coll.removeAll(co);
System.out.println(coll);
//11.equals(Object obj)判断当前集合是否内容一致
Collection coo = new ArrayList();
coo.add(123);
coo.add("范冰冰");
boolean heh = co.equals(coo);
System.out.println(heh);//true
//12.hashCode()根据一定的算法,将当前集合转何为hasCode值
int i = coll.hashCode();
System.out.println("hashCode为:"+i);
System.out.println();
//13.toArray() 将集合转换为数组
Object[] obj = coll.toArray();
for (int j = 0; j < obj.length; j++) {
System.out.println(obj[j]);
}
//14.iterator() 返回一个Iterator接口实现类的对象,进而实现集合的遍历
Iterator ite = coll.iterator();
while (ite.hasNext()) {
Object object = (Object) ite.next();
System.out.println("迭代器遍历:"+object);
}
}