JAVA_SE(三)-集合框架


/* java.util.Collection
 * 集合,用来存储一组元素,提供了相关操作元素的方法.
 * 有两个常见的子接口:
 * List:可重复集,且有序.
 * Set:不可重复集,大部分实现类是无序的.
 * 元素是否重复是依靠元素自身equals方法比较的结果
 * @author within

 */


/**
 * 集合存放的是元素的引用(地址)
 * @author adminitartor
 *
 */
public class CollectionDemo2 {
	public static void main(String[] args) {
		Point p = new Point(1,2);
		
		Collection c = new ArrayList();
		c.add(p);
		
		System.out.println("c:"+c);
		System.out.println("p:"+p);
		
		p.setX(2);
		System.out.println("p:"+p);
		System.out.println("c:"+c);//[(2,2)]
	}
}

class Point{
	private int x;
	private int y;
	
	public Point(int x, int y) {
		super();
		this.x = x;
		this.y = y;
	}
	public int getX() {
		return x;
	}
	public void setX(int x) {
		this.x = x;
	}
	public int getY() {
		return y;
	}
	public void setY(int y) {
		this.y = y;
	}
	
	@Override
	public String toString() {
		return "("+x+","+y+")";
	}
	
}

/**
 * boolean contains(E e)
 * 判断当前集合是否包含给定元素
 * 
 * @author adminitartor
 *
 */

public class Collection_contains {

	public static void main(String[] args) {
		Collection c = new ArrayList();	
		c.add(new Cell(1,2));
		c.add(new Cell(3,4));
		c.add(new Cell(5,6));
		c.add(new Cell(7,8));
		System.out.println(c);
		Cell cell = new Cell(1,2);
		/*
		 * 集合判断是否包含给定元素是根据给定元素
		 * 与集合现有元素equals比较是否有true.
		 */
		boolean contains = c.contains(cell);
		System.out.println("包含:"+contains);
	}
}
class Cell{
	int row, col;
	public Cell(int row, int col) {
		this.row = row;
		this.col = col;
	}
	/*
	 * 重写equals方法(修改父类的方法)
	 *  Cell c1 = new Cell(5,6);
	 *  Cell c2 = new Cell(5,6);
	 *  b = c1.equals(c2) 
	 *  b = c1.equals("5,6") 
	 *  b = c1.equals(c1);
	 *  Cell c3 = null;
	 *  b = c1.equals(c3);
	 */
	public boolean equals(Object obj){
		//方法执行期间 this 是 当前对象引用
		//obj是 另外一个对象的引用
		//比较关键数据: 就是比较this(row,col) 
		//   和 obj(row, col) 是否相等
		if(obj==null){
			return false;
		}
		if(this==obj){//对象自己和自己比较
			return true;//性能好!
		}
		if(obj instanceof Cell){
			Cell other=(Cell)obj;
			return  this.row == other.row && 
				this.col == other.col;
		}
		return false;
	}
	@Override
	public String toString() {
		return "("+row+","+col+")";
	}
}


猜你喜欢

转载自blog.csdn.net/qq_41264674/article/details/80493897