关于集合的部分方法的使用:
package com.raizofeeling.test;
import java.util.ArrayList;
import java.util.Collection;
/**
* CollectionDemo.java description: 集合的使用
* @author raizoo
* Created on 17-7-20 上午8:38.
* @version 1.0
* @since JDK8.0
* @throws Exception:
*
*/
public class CollectionDemo {
public static void main(String[] args){
Collection collect = new ArrayList();
//构建3个元素,cel1、cel2放入集合,cel3不放入集合
Cell cel1 = new Cell(1,2);
Cell cel2 = new Cell(3,4);
Cell cel3 = new Cell(3,4);
//集合里添加元素
collect.add(cel1);
collect.add(cel2);
/*
* Cellection类的方法 description:注意Cellection是接口类型,包含set和list两个子接口:
* list-可重复元素导入其中;set-不可重复元素导入,通过queals()判断要导入的元素和集合中元素是否相像
* 相像-不放入set;不相像-放入set。
* 包含常用方法:
* 1.contains(Object obj):返回值boolean型.判断集合是否包含obj;
* 2.size():返回值int型.集合包含元素的数量;
* 3.isEmpty():返回值boolean型,集合是否为空;
* 4.clear():void,清除集合内元素.
*
*/
// collect.clear();
int size = collect.size(); //包含元素数量
System.out.println("元素有"+size+"个"); //2个
System.out.println("是否包含cel3?"+collect.contains(cel3)); //包含
System.out.println("是否为空:"+collect.isEmpty()); //不为空
System.out.println("cel3与cel2相像否:"+cel3.equals(cel2)); //相像
}
}
package com.raizofeeling.test;
public class Cell {
private int x;
private int y;
public Cell(int x,int y){
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
if(obj == this){
return true;
}
if(obj == null){
return false;
}
if(obj instanceof Cell){
Cell c = (Cell)obj;
return c.x == this.x && c.y == this.y;
}
return false;
}
}