JavaSE入门:迭代器和比较器

迭代器

Iterator,迭代器

语法格式
Iterator it =集合对象.iterator();
在集合中,只要调用集合对象自己的iterator()就能创建这个集合的迭代器

迭代器中的三个方法

  • boolean hasNext() 判断当前游标的下一位是否还有元素,有就返回true,没有就返回false
  • E next() 将迭代器游标向下移动一位,并返回这个数据
  • remove() 删除当前游标指示的元素

原则上,上面三个方法必须按照这个顺序调动,因为这就是一个体系的

Collection c =new ArrayList();
		c.add(1);
		c.add("sdahf");
		c.add(true);
		c.add(3);
		c.add(2.34);
		
		//创建迭代器
		Iterator it =c.iterator();
		//如果添加了数据,不迭代器是不会报错的
		c.add(4);
		//重新生成迭代器
		it =c.iterator();
		//依靠迭代器遍历
		while(it.hasNext()) {
			Object o =it.next();
			System.out.println(o);
		}

注意

  • 迭代器一旦创建,集合中不能添加或着删除元素,如果删除和添加了元素必须重新生成迭代器;更改数据不用
  • 迭代器遍历一遍之后游标(指针)不会返回起始位置,想要再次遍历需要重新生成迭代器
  • 使用迭代器时 ,删除元素只能用迭代器里面的方法删除(不能用用集合的remove)
		Iterator it = c.iterator();
		//迭代器遍历
		while (it.hasNext()) {
			Object object = it.next();
			// 不能使用集合的删除,迭代器创建后,集合不能添加删除元素
			// c.remove(object);

			// 可以使用迭代器的删除,会把迭代器和集合中的都删除
			// 删除当前指向的元素
			it.remove();
		}

比较器

集合想要排序必须要用到比较器

分类

元素自身比较器

Comparable,添加的元素需要实现这个接口,这种情况下一般用于我们自定义的类中,比如我们八种基本数据类型的包装类都实现了这个接口,所以集合和中放置的元素是这八种是可以直接排序的。

list中八种基本类型包装类排序

// 排序
		Collections.sort(集合对象名);

非八种基本数据类型(不仅是list),如果是添加元素自身比较器,那么都得实现Comparable接口。

比较器类

Comparator,常用于改变原有排序,他对元素自身是有覆盖作用的。

他有两种写法,一种是在外面重新设置一个类,一种是在里面写一个匿名内部类。外部设一个类是可以重复使用,而匿名内部类只能使用一次,针对的是当前的。其他不可以调用。

比如Integer是默认升序,我想降序,就需要使用Comparator来重新排序,因为它的优先级高。

外部写比较器类写法:

public static void main(String[] args) {
//		SortedSet products = new TreeSet(new productComparator());
}

//class productComparator implements Comparator {
//
//	@Override
//	public int compare(Object arg0, Object arg1) {
//		// arg0是要添加的元素
//		// arg1是集合中的元素
//		double price1 = ((Product) arg0).price;
//		double price2 = ((Product) arg1).price;
//		if (price1 == price2) {
//			return 0;
//		} else if (price1 > price2) {
//			return 1;
//		} else {
//			return -1;
//		}
//	}
//
//}

匿名内部类写法

public static void main(String[] args) {
		SortedSet products = new TreeSet(new Comparator() {
			
			@Override
			public int compare(Object o1, Object o2) {
				// o1是要添加的元素
				// o2是集合中的元素
				double price1 = ((Product) o1).price;
				double price2 = ((Product) o2).price;
				if (price1 == price2) {
					return 0;
				} else if (price1 > price2) {
					return 1;
				} else {
					return -1;
				}
			}
		});
}

猜你喜欢

转载自blog.csdn.net/lfz9696/article/details/107799927