Java List Set 集合的使用

一、List 添加、遍历集合的使用

1.1、List 语法:

List<值类型/引用类型> list=new ArrayList<值类型/引用类型> ();

list.add(值类型/引用类型);添加

举例说明:

假如项目中定义了一个UserEntity实体,他的属性有getId(),getName();setId(),setName();

List<UserEntity>li=new ArrayList<UserEntity>();--定义集合

UserEntity userentity=new UserEntity (); --实例化对象

userentity.setId(1); --属性赋值

userentity.setName("xxxx");

list.add(userentity);--添加集合中

1.2、遍历集合 【三种循环方式】

1.2.1 根据索引回获取对象

for (int i=0;i<li.size();i++)

{

UserEntity userentity = li.get(i); --根据索引回获取对象

}

1.2.2、根据迭代器遍历集合

Iterator t=li.iterator();

while( t.hasNext())

{

UserEntity userentity = (UserEntity)t.next(); --该方法返回的object 方法 需要强制转换下

}

1.2.3、for each遍历集合

for (UserEntity en : li)

{

输出值

}

二、Set 添加、遍历集合的使用

2.1、Set语法

Set<值类型/引用类型> se=new HashSet<值类型/引用类型> ();

se.add(值类型/引用类型);添加

举例说明:

假如项目中定义了一个UserEntity实体,他的属性有getId(),getName();setId(),setName();

Set<UserEntity> se=new HashSet<UserEntity>();--定义集合

UserEntity userentity=new UserEntity (); --实例化对象

userentity.setId(1); --属性赋值

userentity.setName("xxxx");

se.add(userentity);--添加集合中

2.2、Set遍历 只能用for each遍历

for(UserEntity u :se)

{

输出....................

}

三、查看list 是否包含

语法: contains

如果用新建的实体对象并赋值属性,需要注意将eqals 方法重写。

如果没有新建对象怎不需要重写equals 方法。

例如:

UserEntity entity =list.get(0); 0--代表索引位置

li.contains(entity );结果返回true --如果存在返回true;否则返回false;

UserEntity ue=new UserEntity('','');

li.contains(entity );结果返回false,必须重写equals --如果存在返回true;否则返回false;

四、查看set是否包含

如果用新建的实体对象并赋值属性,需要注意将HashCode方法重写。

Set<UserEntity> Se=new HashSet<UserEntity>();

Se.add(实体对象); ---Set 中添加已有的数据

--新建一个实体对象

UserEntity newEntity =new UserEntity();

newEntity .属性赋值。

se.contains(newEntity );--如果没有HasCode 重写 返回的false,如果重写 返回true;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值