java-集合类(二)-迭代器-Iterator-Collections类自然排序
来源:互联网 发布:mac word转pdf 白边 编辑:程序博客网 时间:2024/06/05 06:43
迭代器方法:
迭代器的工作原理:
注意:迭代器是指向两个元素之间的位置,如果后面有元素则hasNext()返回真,当我们调用next()方法时,返回黄色的元素,如上图,当我们调用remove方法是要先调用一次next(),调用remove将返回的元素删除.
容器的最大作用实例:
package ArrayList;import java.util.ArrayList;import java.util.Arrays;import java.util.Collection;import java.util.Iterator;import java.util.List;class ArrayListTest { //容器的最大作用 public static void printElements(Collection c){ Iterator it = c.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } public static void main(String[] args) { ArrayList al = new ArrayList(); al.add(new Point(3,3)); al.add(new Point(4,4)); printElements(al); }}class Point{ int x,y; Point(int x,int y){ this.x = x; this.y = y; } public String toString(){ return "x=" + x +","+"y=" + y; }}
Collections类
排序:Collections.sort()
(1)自然排寻(natural ordering );
(2)实现比较器(Comparator)接口。
package ArrayList;import java.util.ArrayList;import java.util.Arrays;import java.util.Collection;import java.util.Collections;import java.util.Iterator;import java.util.List;class ArrayListTest { public static void printElements(Collection<?> c) { Iterator<?> it = c.iterator(); while(it.hasNext()){ System.out.println(it.next()); } } public static void main(String[] args) { Student s1 = new Student(5, "xiaoxi"); Student s2 = new Student(2, "xiaohong"); Student s3 = new Student(3, "xiaozhu"); ArrayList<Student> al = new ArrayList<Student>(); al.add(s1); al.add(s2); al.add(s3); //Collections类进行排序,自然排序 Collections.sort(al); printElements(al); }}class Student implements Comparable<Object> { int num; String name; Student(int num, String name) { this.name = name; this.num = num; } @Override public int compareTo(Object arg0) { Student s = (Student) arg0; //如果当前数比你要比较的数大返回1,小,返回负数 return num > s.num ? 1 : (num == s.num ? 0 : -1); } public String toString() { return "num=" +num + ", name=" + name; }}
结果
num=2, name=xiaohongnum=3, name=xiaozhunum=5, name=xiaoxi
0 0
- java-集合类(二)-迭代器-Iterator-Collections类自然排序
- [Java 13 类集合] Iterator, Properties, Collections
- java集合类(二)Collections类内元素排序
- Java集合工具类Collections(二)
- Java集合框架->Collections类
- Java 集合工具类 Collections
- Java 集合工具类Collections
- java集合(工具类Collections)
- java Collections集合工具类
- Java 集合工具类 Collections
- Java集合-Collections类详解
- Java--Collections集合工具类
- java集合排序 Collections.sort
- 集合工具类Collections.sort()排序方法
- java集合操作的包装类Collections(包含集合的排序)
- Java集合类的学习(二)——Collection接口和Iterator迭代器
- java集合(TreeSet自然排序)
- 集合排序--自然排序
- uva 11552(dp)
- (十六)yii2 视图中渲染到另一个视图中
- 简单链表操作
- Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL
- 关于苹果《Genius Bar 天才吧》预约流程
- java-集合类(二)-迭代器-Iterator-Collections类自然排序
- linux系统-进程管理-基本概念和命令
- objective_c 第九章课后练习题答案
- 湘潭大学oj 1195
- Difference between “git add -A” and “git add .” and "git add -u"
- 学习SQL Server推荐的10本书
- android知识点
- 4.HCNP-R&S-IERN——建立OSPF邻居与邻接关系
- sa5ssd74sg39