0
点赞
收藏
分享

微信扫一扫

java集合--Collection

倚然君 2022-04-17 阅读 69
javaeclipse

1.什么是集合


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

  • 和数组区别: 

  •  1.数组长度固定,集合长度不固定

  • 2.数组可以存储基本类型和引用类型,集合只能存储引用类型

  • 位置import :java.util.*;

Collection体系集合


 

package Collection;
import java.util.*;

public class Demo1 {
public static void main(String[] args) {
//创建集合
Collection collection = new ArrayList();
//*(1).添加元素
collection.add("苹果");
collection.add("西瓜");
collection.add("榴莲");
System.out.println("元素个数: "+collection.size());
System.out.println(collection);
//*(2).删除元素
// collection.remove("榴莲");
// collection.clear();
// System.out.println("删除之后的元素:"+collection.size());
//*(3).遍历元素
System.out.println("----------使用增强for-------");//foreach遍历数组
for (Object object:collection) {
System.out.println(object);
}
//3.2使用迭代器(迭代器专门用来遍历集合的一种方式)
//hasNext();没有下一个元素
//remove();删除当前元素
System.out.println("-------------3.2使用迭代器-------------");
Iterator it = collection.iterator();
while (it.hasNext()){
String s = (String)it.next();
System.out.println(s);
//不能使用collection删除方法
//collection.remove(s)
//it.remove();
}
System.out.println("元素个数: "+collection.size());
// *4.判断
System.out.println(collection.contains("西瓜"));//判断是否有西瓜元素
System.out.println(collection.isEmpty());//判断是否为空
}


}

 

 实列二

package Collection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
*Colleciond的使用保存学习信息
*
*/

public class Demo2 {
public static void main(String[] args) {
//新建Collection对象
Collection collection = new ArrayList();
Student s1 = new Student("张三",10);
Student s2 = new Student("李四",10);
Student s3 = new Student("王五",22);
//添加数据
collection.add(s1);
collection.add(s2);
collection.add(s3);
System.out.println("元素个数: "+collection.size());
System.out.println(collection.toString()); //学生类中打印的事toString

//2.刪除
// collection.remove(s1);
// collection.remove(new Student("张三",10));
// collection.clear();
// System.out.println("元素个数: "+collection.size());
//3遍历
System.out.println("-----------增强for---------");
for (Object Object:collection) {
Student s = (Student) Object ;
System.out.println(s.toString());
}
//3.2迭代器:hasNext() ;迭代过程中不能使用collection的删除方法
System.out.println("-------------------迭代器-------------");
Iterator it = collection.iterator();
while (it.hasNext()){
Student s = (Student) it.next();
System.out.println(s.toString());
}
//判断
System.out.println(collection.contains(s1));
System.out.println(collection.isEmpty());
}



}

 学生类

package Collection;

/**
* 学生类
*
*/

public class Student {
private String name ;
private int age ;

public Student(String name, int age) {
this.name = name;
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}

 

 

 

 

举报

相关推荐

0 条评论