Java学习笔记(8)——集合
集合
- 概念:能够存储任意数量的具有相同属性对象的工具类。
- 作用:
- 在类的内部对数据进行组织;
- 可以简单快速的搜索大量的数据
- 有的集合接口提供了一系列排列有序的元素,可以供用户快速的插入或删除某个元素;
有的集合接口提供了映射关系,可以通过关键字(key)快速查找到对应的唯一对象,而且关键字的类型可以是任意的。
- 集合与数组的区别:
数组的长度是固定的,定义了之后就无法更改;集合的长度是可变的,可随着数据量不断扩增;
数组只能通过下标来确定元素,而集合可以通过任意类型查找对应的元素。
- Java集合框架
Collection
<根接口>
只存储对象
Map
<根接口>
以< key, value >两个对象
组成一个映射来存储一个数据
List
序列
有序可重复
Queue
队列
有序可重复
Set
集
无序不可重复
ArrayList
LinkedList
HashSet
HashMap
Collection接口
- Collection接口是List、Queue、Set接口的父接口;并且定义了可操作List、Queue、Set的增删改查的方法。
- Collection方法:
List
- List的元素有序排列,且可以重复,被称为序列;
- List可以精确的控制每个元素的插入或删除的位置;
- ArrayList——数组序列,是List的一个重要的实现类;
- ArrayList底层是由数组实现的。
ArrayList添加元素:
private List cCourse = new ArrayList();
@Override
public void addCourse() {
// TODO Auto-generated method stub
Course c = new Course("1", "book1");
Course c1 = new Course("2", "book2");
Course[] course = {
new Course("3", "book3"),
new Course("4", "book4")
}
//添加一个对象到cCourse
cCourse.add(c)
//添加一个对象到cCourse的指定位置,如果index大于当前集合的长度,就会产生数组越界异常
cCourse.add(0, c1);
//还可以使用addAll(Collection c)方法,添加一个集合到另一个数组序列
//在这里可以调用Arrays中的方法asList()将数组转换成集合
cCourse.addAll(Arrays.asList(course));
//也可以为其指定插入的对象
cCourse.addAll(1, Arrays.asList(course));
//将第一个对象取出,取出的d对象类型会被设置为Object类,所以需要强制类型转换成原本的类型
Course temp = (Course) cCourse.get(0);
System.out.println("course:" + temp.getCourseId() + "," + temp.getCourseName());
}
ArrayList遍历元素
//利用for循环遍历集合中的元素
public void printCourse(){for(int i = 0;i < cCourse.size();i++){
Course temp = (Course)cCourse.get(i);
System.out.println(temp.getCourseId() + "," + temp.getCourseName());
}
}
//利用迭代器的方法遍历数组中的元素
public void printIterator(){Iterator it = cCourse.iterator();
for(it.hasNext()){
Course temp = (Course)it.next();
System.out.println(temp.getCourseId() + "," + temp.getCourseName());
}
}
//利用foreach方法遍历数组
public void printForeach(){for(Object o : cCourse){
Course temp = (Course)o;
System.out.println(temp.getCourseId() + "," + temp.getCourseName());
}
}
ArrayList修改元素
//修改数组序列中的某个元素
public void Modify(){cCourse.set(1, new Course("2", "book2"));
}
ArrayList删除元素
//删除某一指定的元素
public void removeByObj(){cCourse temp = (cCourse)cCourse.get(0);
cCourse.remove(temp);
}
//删除某一指定位置的元素
public void removeByIndex(){cCourse.remove(0);
}
//删除某一数组中的元素
public void removeByArray(){Course[] courses = {
(Course)cCourse.get(0),
(Course)cCourse.get(1)
};
cCourse.removeAll(Arrays.asList(courses));
}
泛型
- 集合中的元素,可以是任意类型的元素,如果把一个类型放入集合,他会自动忽略他的类型,按Object类型处理;
- 泛型则是规定了某个集合只能放入指定类型或其子类型,会在编译时检查存入的类型是否符合,并且在取出时也按该指定类型取出,不需要再进行类型转换;
- 泛型不能指定基本类型,但是可以指定基本类型的包装类。
例:
//加入泛型后的用迭代方法输出集合的方法
public void printIterator(List<Course> choiceCourse) {
Iterator<Course> it = choiceCourse.iterator();
while(it.hasNext()) {
Course temp = it.next();
System.out.println(temp.getCourseId() + "," + temp.getCourseName());
}
}
public void testBasicType(){
List<Integer> i = new ArrayList<Integer>();
//为i集合添加元素1时,会自动将基本类型转换为包装类(装箱),所以在编辑时不会报错
i.add(1);
System.out.println(i.get(0));
}
Set
- Set中的元素都是无序且不可重复的;
- HashSet——Set的重要实现对象,并且在其方法中不存在修改元素的方法;
- Set中的方法与ArrayList的方法相似,但是Set中没有get()方法,因为Set集是无序的,只能用迭代的方法的去输出元素。并且无论添加多少次相同的元素,最终只会保存第一个加入的元素,且数量不会增加;
- Set集可以添加空元素。
Map接口
- Map提供了一种映射关系,其中的元素都是以键值对(value,key)形式存储的,能够实现通过key快速查找value;
- Map中的键值对以Entry类型的对象实例存在;
- key值不可以重复,value值可以重复;
- 每个键最多只可映射到一个值;
- Map接口提供了返回key值集合,value值集合和Entry集合的方法;
- Map支持泛型(Map
)。 - Map的方法:
- HashMap:是Map的重要实现类,基于哈希表实现。在HashMap中Entry对象是无序排列的,且key值和value值都是可以为null,但是只能有一个key值为null的映射。
HashMap添加元素
public Map
stu = new HashMap (); public void addStu(){
Scanner scanner = new Scanner(System.in);
int i = 0;
//循环输入3名学生的信息,并放入Map集合中
while(i < 3) {
System.out.println("enter student's ID:");
String stuId = scanner.next();
//判断输入的序号在集合中是否存在,若不存在输入学生姓名
if(stu.get(stuId) == null) {
System.out.println("enter student's name:");
String stuName = scanner.next();
//调用put(key,value)将学生对象放入集合中
stu.put(stuId, new Students(stuId, stuName));
System.out.println("student " + stu.get(stuId).getStuName() + " has been added.");
i++;
}else {
System.out.println("This Id has been occupy, please enter other Id");
continue;
}
}
}
HashMap元素遍历
//通过获取key值来遍历元素
@Override
public void print() {
// TODO Auto-generated method stub
// 调用keySet()方法,将Map中的key存入一个Set集合中
Set<String> keySet = stu.keySet();
for (String str : keySet) {
Students s = stu.get(str);
System.out.println(s.getStuId() + "," + s.getStuName());
}
}
//通过获取键值对(Entry)来遍历元素
@Override
public void printEntry() {
// TODO Auto-generated method stub
// 调用entry()方法来创建一个Set集合存放键值,泛型规定为Entry类型,其中Entry也要用键值规范
Set<Entry<String, Students>> entrySet = stu.entrySet();
System.out.println("Print the students after remove student");
for (Entry<String, Students> entry : entrySet) {
System.out.println(entry.getKey() + "," + entry.getValue().getStuName());
}
}
HashMap删除某一元素
@Override
public void remove() {
// TODO Auto-generated method stub
System.out.println("please enter Id which do you want to remove.");
Scanner scanner = new Scanner(System.in);
String stuId = scanner.next();
while(true) {
if(stu.get(stuId) == null) {
System.out.println("This Id is invail, please enter other Id.");
continue;
}
stu.remove(stuId);
break;
}
}
HashMap修改元素
@Override
public void modify() {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("please enter the Id which you want to modify");
String stuId = scanner.next();
if(stu.get(stuId) == null) {
System.out.println("This Id is invail, please enter other Id");
continue;
}
System.out.println("enter the name modified:");
String stuName = scanner.next();
//HashMap修改元素也是用put()来修改,第一个值是现有的key
stu.put(stuId, new Students(stuId, stuName));
break;
}
}
判断某一对象是否在当前集合中:
判断某一对象是否存在List集合中
public void isContain(List
choiceCourse) { Course c = new Course();
Scanner scanner = new Scanner(System.in);
System.out.println("enter the course name :");
String stuName = scanner.next();
c.setCourseName(stuName);
//调用contains(Object o)方法,来判断输入元素是否存在于当前集合中
System.out.println(choiceCourse.contains(c));
}
contains(Object o)判断的方法基于equals()方法,调用集合中的每一个元素的equals()方法判断是否与该对象相等。在调用源代码中的equals()方法判断的是指向对象的地址是否相等,所以如果新建一个对象,则两个对象一定不等,故需要重写equals()方法,判断元素中的值是否相等。
判断某一对象是否存在Set集合中
@Override
public void isStuCourse(Students s) {
// TODO Auto-generated method stub
System.out.println("please enter course name:");
Scanner scanner = new Scanner(System.in);
String stu_c = scanner.next();
Course c = new Course();
c.setCourseName(stu_c);
System.out.println(s.getCourse().contains(c));
}
Set集合中判断对象是否存在,是需要校验他们的HashCode若HashCode相同,则调用equals()方法判断是否相同,所以需要在Course类中重写hashCode方法和equals()方法。
判断某一元素在List集合中的索引位置
public void isContain(List
choiceCourse) { Course c = new Course();
Scanner scanner = new Scanner(System.in);
System.out.println("enter the course name :");
String stuName = scanner.next();
c.setCourseName(stuName);
System.out.println(choiceCourse.contains(c));
if(choiceCourse.contains(c))
System.out.println(choiceCourse.indexOf(c));
}
indexOf(Object o)方法主要调用的是equals()方法,判断集合中是否含有要查找的对象,若是存在,则输出它的索引位置。若List集合中含有多个元素则只输出第一元素所在的索引位置。lastIndexOf()方法类似只输出最后一个元素的索引位置。若没有查找到要查找的对象则输出-1。
判断Map集合中是否存在对应的key值和value值
@Override
public void isStuKey() {
// TODO Auto-generated method stub
System.out.println("please enter stu Id:");
Scanner scanner = new Scanner(System.in);
String stuId = scanner.next();
if(stu.containsKey(stuId))
System.out.println("student " + stu.get(stuId).getStuName() + " is contain.");
else
System.out.println("student " + stuId + " isn't contain.");
System.out.println("please enter stu name:");
String stuName = scanner.next();
if(stu.containsValue(new Students(null, stuName)))
System.out.println("student " + stuName + " is contain.");
else
System.out.println("student " + stuName + " isn't contain.");
}
调用containsKey(Object key)
方法可以直接判断Map中是否有对应的元素。但在调用containsValue(Object value)
方法时需要重写hashCode()方法和equals()方法,与contain()方法原理类似。
对集合中的元素进行排序
对Integer/String类型进行排序
Collections工具类是Java集合框架中操作集合元素的工具类,调用sort(List<T> List)
方法对集合中的元素进行排序。//对Integer类型进行排序
public void sortInt() {
List<Integer> intList = new ArrayList<Integer>();
Random r = new Random();
Integer k;
for (int i = 0; i < 10; i++) {
do {
k = r.nextInt(100);
} while (intList.contains(k));
intList.add(k);
System.out.println("add number " + k + " success.");
}
System.out.println("---------------------------------------------");
System.out.println("---------print number before sort----------");
for (Integer integer : intList) {
System.out.println(">>>>>>>>>>number:" + integer);
}
Collections.sort(intList);
System.out.println("----------print number after sort-----------");
for (Integer integer : intList) {
System.out.println(">>>>>>>>>>>number" + integer);
}
}
//对字符串类型进行排序
public void sortString() {
List<String> strList = new ArrayList<String>();
strList.add("China");
strList.add("English");
strList.add("Canada");
System.out.println("----------print string before sort------------");
for (String string : strList) {
System.out.println(">>>>>>>>str:" + string);
}
System.out.println("----------print string after sort--------------");
Collections.sort(strList);
for (String string : strList) {
System.out.println(">>>>>>>>str:" + string);
}
}
对某一类型进行比较
- Comparable接口
实现该接口表示:这个类的实例可以比较大小,可以进行自然排序;
定义了默认的排序规则;
其实现类需要实现compareTo()方法;
compareTo()方法返回值为正则表示大,返回值为负表示小,返回0表示相等。 - Comparator接口——比较工具接口
用于定义临时的比较规则,而不是默认的规则;
其实现类需要实现compare()方法;
Comparator和Comparable接口都是Java集合框架的成员。
例:
public void sortCourse() {
// TODO Auto-generated method stub
System.out.println("-----------print course after sort--------------");
// 需要对Course类继承Comparable<T>接口,并实现compareTo()方法
// 调用Collections的sort(List<T> list)方法,对对象进行默认方法的排序
Collections.sort(cCourse);
printIterator();
System.out.println("-----------print course after sort by name--------------");
// 需要创建一个类作为比较,继承Comparator<T>接口,并实现compare()方法
// 调用Collections的sort(List<T> list, Comparator<? super T> c)方法,对对象进行临时排序
Collections.sort(cCourse, new HandleCourse());
printIterator();
}
- Comparable接口
Course类继承Comparable接口
@Override
public int compareTo(Course c) {
// TODO Auto-generated method stub
return this.courseId.compareTo(c.courseId);
}
handlCourse类继承Comparator接口
@Override
public int compare(Course arg0, Course arg1) {
// TODO Auto-generated method stub
return arg0.getCourseName().compareTo(arg1.getCourseName());
}
还没有评论,来说两句吧...