ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

自动化测试学习过程中遇到的JAVA知识(一)Collection接口的使用

2022-07-11 16:05:42  阅读:128  来源: 互联网

标签:Collection JAVA -- System collection add 接口 println out


Collection体系:

 

 

 

 

集合的概念:对象的容器,定义了对多个对象进行操作的常用方法,可实现数组的功能。

和数组的区别:①数组长度固定,集合长度不固定

         ②数组可以存储基本类型和引用类型,而集合只能存储引用类型。

 

 

Collection接口的使用:①添加元素--add();②删除元素--remove();③遍历元素--可用增强的for循环,也可使用迭代器Iterator。

 

/**
* Collection接口的使用
* 1.添加元素
* 2.删除元素
* 3.遍历元素
* 4.判断
* @author 长空扯淡
*/
public class Demo01 {
public static void main(String[] args) {

//创建集合
Collection collection = new ArrayList();
// * 1.添加元素
collection.add("西瓜");
collection.add("香蕉");
collection.add("火龙果");
System.out.println(collection);//输出--[西瓜, 香蕉, 火龙果]

System.out.println("===========================");

// * 2.删除元素
collection.remove("香蕉");
//collection.clear();//清除
System.out.println("删除之后:"+collection.size());//输出--删除结果:2

System.out.println("===========================");

// * 3.遍历元素【重点】
//3.1用增强的for循环
for(Object obj:collection){
System.out.println(obj);//输出--西瓜
}                     火龙果
System.out.println("===========================");

//3.2使用迭代器(专门用来遍历集合的一种方式)
/*
hasNext();有没有下一个元素
next();获取下一个元素
remove();删除当前元素
*/
Iterator it = collection.iterator();
while(it.hasNext()){
String s = (String)it.next();
System.out.println(s);        //输出--西瓜                                  火龙果
//不允许使用collection.remove();的删除方法,可以使用it.remove();
//it.remove();
}
System.out.println(collection.size());//输出结果--2

// * 4.判断
System.out.println("===========================");

System.out.println(collection.contains("西瓜"));//输出--true
System.out.println(collection.isEmpty());//输出--false
}
}

也可以用add()方法添加对象

//假设Student类已经定义好
Student s1 = new Student("爱丽丝",17);
Student s2 = new Student("桐人",17);
Student s3 = new Student("优吉欧",17);

//新建Collection对象
Collection collection = new ArrayList();
//1.添加数据
collection.add(s1);
collection.add(s2);
collection.add(s3);
System.out.println(collection);
System.out.println(collection.size());

 

转载:https://www.cnblogs.com/55yyy/p/16055984.html

标签:Collection,JAVA,--,System,collection,add,接口,println,out
来源: https://www.cnblogs.com/momoyou/p/16466728.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有