首页 > 其他 > 详细

collection类

时间:2021-05-16 19:09:19      阅读:23      评论:0      收藏:0      [点我收藏+]

Collection 的概述和使用

collection需要新建一个对象

 Collection<String> c =new ArrayList<String>();//存储string类型 //实例化

插入

//添加元素add();
        c.add("hello");
        c.add("world");
        c.add("java");
        System.out.println(c);

常用方法

add();插入元素

boolean remove();移除集合中制定元素

成功返回true

失败返回false

 System.out.println(c.remove("hello"));

 

clear();清空集合中元素

c.clear();
System.out.println(c.isEmpty());

返回true;

 

boolean contains();判断集合中是否存在指定元素

System.out.println(c.contains("world"));

 

boolean isEmpty();判断集合中是否存在元素

size ();集合的长度

 

collection的遍历

 Iterator<String> it =c.iterator() ;

获取元素前应该进行判断

   if(it.hasNext()){
            System.out.println(it.next());
            
        }

用循环改进

  while(it.hasNext()){
         System.out.println(it.next());

     }
  while(it.hasNext()){
         String s=it.next();
         System.out.println(s);

     }

示例  使用collection存储学生对象

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Collection;
import java.util.ArrayList;
//定义学生类
//创建collection对象
//创建学生对象
//把学生添加到集合
public class collectiondemo {
    public static  void main(String[] args) {
        Collection<Student> c=new ArrayList<Student>();
        Student s1=new Student("1",19);
        Student s2=new Student("2",18);
        Student s3=new Student("3",20);

        c.add(s1);
        c.add(s2);
        c.add(s3);
        //遍历集合
        Iterator<Student> it =c.iterator();
        while(it.hasNext()){
            Student s=it.next();
            System.out.println(s.getName()+s.getAge());


        }


    }

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

 

collection类

原文:https://www.cnblogs.com/sjyoops/p/14774143.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!