您的位置:首页 > 编程语言 > Java开发

Java集合类的混淆点总结(一)

2016-05-16 22:01 686 查看
在校大三渣渣学生,但有一个热爱程序的心。欢迎吐槽,互相交流。

Java集合类主要负责保存、盛装其他数据,因此集合类也称容器类。接下来的几天,博主梳理下博主在集合类遇到一些坑。

1》Compartor和Comparable接口的区别

1.Comparable的接口实现方法

public int comparTo(Object o){}

2.Compartor的接口实现方法

public int compare(Student o1,Student o2){}

3.Comparator位于包java.util下,而Comparable位于包
java.lang下

使用情景:Comparable只能规定一种sort的方式, 当class中有多个字段是时候,可以使用Comparator的方式,多个类实现Comparator接口,实现按照不同的字段(你所定义的)去实现排序。

具体的代码:

class Student implements Comparable<Object>{

public String name;
public int age;
public int grade;
public Student(String name,int age,int grade) {
// TODO Auto-generated constructor stub
this.name=name;
this.age=age;
this.grade=grade;
}
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
Student s=(Student)o;
if(this.age>s.age){
return 1;
}else if(this.age==s.age){
return 0;
}
else{
return -1;
}
}
}
//自定义的比较器
class MyCompartor implements Comparator<Student>{

@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
if(o1.grade<o2.grade)
return 1;
else if(o1.grade == o2.grade)
return 0;
else
return -1;
}

}

public class test{
public static void main(String[] args) {
List<Student> stuLists=new ArrayList<Student>();
stuLists.add(new Student("yang0", 11,98));
stuLists.add(new Student("yang1", 9,89));
stuLists.add(new Student("yang2", 13,70));
stuLists.add(new Student("yang3", 10,69));
Collections.sort(stuLists);
for(Student stu:stuLists){
System.out.println(stu.name+"=>"+stu.age);
}
Collections.sort(stuLists, new MyCompartor());
for(Student stu:stuLists){
System.out.println(stu.name+"=>"+stu.grade);
}

}
}


2》Iterator

迭代器们最常使用的是使用迭代器进行遍历集合中元素

hasnext()

Returns true if the iteration has more elements. (In other words, returns true if next would return an element

rather than throwing an exception.)

返回真如果迭代器还有更多的元素(换言之,返回真如果还有下一个元素而是抛出异常)

next()

Returns the next element in the iteration. 返回下一个元素

这里的next()图解



应该将Java迭代器的认为是位于两个元素之间。当调用next(),迭代器就越过下一个元素,并返回刚刚越过的那个元素的引用。
!!!还有就是对Java集合遍历删除是必须要单独使用迭代器或者单独使用Arraylist集合。
不可以将Iterator和Attaylist数据混乱使用。(经常报错)

①.Iterator<Student> it=stuLists.iterator();

while(it.hasNext()){

Student s=it.next();

if(s.name.contains("yang")){

stuLists.remove(s); //删除元素

}

}
报错信息:

java.util.ConcurrentModificationException

at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:966)

at java.util.LinkedList$ListItr.next(LinkedList.java:888)

at test.main(test.java:69)

正确代码:

②. Iterator<Student> it=stuLists.iterator();

while(it.hasNext()){

Student s=it.next();

if(s.name.contains("yang")){

it.remove();

}

}

实际中:Arraylist采用Size维护自己的自己状态,而Iterator使用采用游标(Cursor)来维护自己的状态。当size改变是,Cursor并未及时更新。除非这种变化是Iterator是自己更新的。

第二个代码使用it.remove()时候,游标引发Arraylist的Size发生改变同时自己游标也同步更新。

第一种代码使用stuLists.remove(),Arraylistd的Size发生改变时并没有通知Cursor同步更新

抛出异常(checkForComodification)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: