java-CollectionDemo

关于集合的部分方法的使用:

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;
        }
    }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值