java容器类

参考http://docs.oracle.com/javase/tutorial/collections/interfaces/index.html

Java容器类不能存放基本类型,比如int。


List可以通过Collections.sort的方式进行排序

若List中存储的元素已经实现comparable类型,则直接调用Collections.sort方法即可,否则需实现Comparable接口。

或者调用Collections.sort的两个参数版本的函数,第2个参数传递一个Comparator对象即可


Comparable接口由下面的方法组成

public interface Comparable<T> {
    public int compareTo(T o);
}


Comparator

如果想排序没有实现Comparable接口的对象,或者不按照自然顺序排序,这时便需要提供一个Comparator



 Comparator接口只包含一个方法

public interface Comparator<T> {
    int compare(T o1, T o2);
}

The compare method compares its two arguments, returning a negative integer, 0, or a positive integer depending on whether the first argument is less than, equal to, or greater than the second. If either of the arguments has an inappropriate type for the Comparator, the compare method throws a ClassCastException


其中介绍了Comparator的方法中为了比较两个数的大小使用了

return e1.number() - e2.number();

跟我之前实现的一样。这种是有潜在的bug的,oracle的tutorial中介绍因为可能前一个数是个很大的正数,后一个数是很小的复数,两数之差可能导致溢出


下例是用Collections.sort方法对容器中的对象进行排序的例子。

需实现Comparator类及Comparator类中的sort方法

import java.util.*;

class Car {
	public Car(int m) {
		this.price = m;
	}
	public int getPrice() {
		return this.price;
	}
	private int price;
};

public class Test {
	public static void main(String[] args) {

		// List is a interface

		List<Car> l = new ArrayList<Car>();
		l.add(new Car(5));
		l.add(new Car(9));
		l.add(new Car(8));
		l.add(new Car(7));
		for (Car i : l) {
			System.out.println(i.getPrice());
		}
		Collections.sort(l, new Comparator<Car>() {
			// a negative integer, zero, or a positive integer as this object
			// is less than, equal to, or greater than the specified object
			@Override
			public int compare(Car arg0, Car arg1) {
				// TODO Auto-generated method stub
				// potential risk,maybe overflow
				// return arg0.getPrice()-arg1.getPrice()
				return (arg0.getPrice() < arg1.getPrice() ? -1 : (arg0
						.getPrice() == arg1.getPrice() ? 0 : 1));

			}
		});

		Iterator<Car> iter = l.iterator();
		while (iter.hasNext()) {
			Car c = iter.next();
			System.out.println(c.getPrice());
		}

	}
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值