Collection
1.格式public interface Collection<E>
extends Iterable<E>
2.contains()方法,containsAll()方法要重写equals(),hashcode()方法。
3.hashcode是用于散列数据的快速存取,如利用HashSet等。
4.迭代器使用在博客:https://mp.csdn.net/postedit/98510102
Collection<Student> collection = new ArrayList<Student>();
Student student = new Student("张", 12, "java");
// 1.add(E e) :增加一个集合元素(增加一个Student类对象)。
collection.add(student);
Collection<Student> collection1 = new ArrayList<Student>();
collection1.add(new Student("李", 18, "英语"));
collection1.add(new Student("王", 20, "语文"));
// 2.addAll(Collection<? extends E> c) :将另一个集合的元素全部增加到集合中
collection.addAll(collection1);
//3.clear()
collection1.clear();
System.out.println(collection1.size());
//4.contains(Object o)
System.out.println("contains()方法:" +collection.contains(student));
System.out.println("contains()方法new Student()对象:" +collection.contains(new Student("张", 12, "java")));
//5.containsAll(Collection<?> c)
Collection<Student> collection2 = new ArrayList<Student>();
Student student2 = new Student("张", 12, "java");
collection2.add(student2);
System.out.println("containsAll()方法:" + collection.containsAll(collection2));
//定义个两个泛型为Student的Arrayslist,明明两个对象一模一样,为什么使用containsAll返回false
//hashCode()可能不一样,需要重写equals(),hashCode()方法。
//要用containsAll,是需要重写Student的equals方法
//6.equals(Object o) //两个集合必须一样。。。
System.out.println("equals()方法,一个为另一个的子集:" +collection.equals(collection2));
collection2.add(new Student("李", 18, "英语"));
collection2.add(new Student("王", 20, "语文"));
System.out.println("equals()方法:" + collection.equals(collection2));
//6.hashCode()返回值类型为int
System.out.println("hashCode()方法:" + student.hashCode());
//7.isEmpty()
System.out.println("isEmpty()方法:" +collection1.isEmpty());
//8.iterator() 迭代器(本方法在集合的遍历中有写)
//9.remove(Object o)
collection.remove(student);
for (Student s : collection) {
System.out.println(s);
}
//10.removeAll(Collection<?> c) 移除两个集合的交际
collection.remove(collection2);
System.out.println("removeAll()方法移除交集元素:" +collection.size());
//11.将集合转化为数组
//11(1)第一种方法:toArray()传一个长度为0的数组。
Student[] students = collection.toArray(new Student[0]);
for (Student student3 : students) {
System.out.println(student3);
}
//11(2)第二种方法:定义好数组,再将集合传给数组
Student[] students2 = new Student[collection.size()];
collection.toArray(students2); //toArray(T[] a)
for (Student student3 : students2) {
System.out.println(student3);
}
//12.将数组转化为集合
Arrays.asList(students);//调用数组的方法
List<Student> list = Arrays.asList(students);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
et/HashMap/Hashtable类来存储数据时,都是根据存储对象的hashcode值来进行判断是否相同的。