java--集合


Collection接口中定义的法:

intsize()

获取集合容器中元素的个数


booleanisEmpty()

集合容器是否为空,即没有元素


void clear() 

清空集合容器中的所有元素


boolean contains(Object element)

集合容器中是否存在某个元素


boolean add(Object element)

向集合容器中添加个元素


boolean remove(Object element)

从集合容器中移除个元素


boolean containsAll(Collection c)

集合容器中是否包含个容器中所有的元素

boolean addAll(Collection c)

将传的集合容器c中的所有元素添加到当前的集合容器

boolean removeAll(Collection c)

从当前集合容器中移除集合容器c中的所有元素

boolean retainAll(Collection c)

当前集合容器和传的集合容器之间是否存在交集

Collection中定义的

Collection容器

Collection定义了存取组对象的法,其Set和List分别定义了存储

集合框架(容器)

Object[] toArray()

将集合容器转换为个对象数组

Iterator iterator()

迭代集合容器中的元素

 

@Test

     public void test1(){

         /**

          * java泛型:类型参数化

          */

         //创建List集合容器

         List<String> ls=new ArrayList<String>();

         ls.add("1");//向集合中添加元素

         ls.add("2");

         ls.add("3");

         ls.add("4");

         //通过get方法获取索引为xx的值

         String test=ls.get(0);

         System.out.println(test);

         //for循环遍历  size获取元素的个数类似数组中的length

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

              String element=ls.get(i);

              System.out.println(element);

         }

        

         //forEach遍历集合

         for(String element:ls){

              System.out.println(element);

         }

         //通过迭代器遍历集合

         Iterator<String>itr=ls.iterator();//创建的List集合容器的参数ls,有获取iterator的方法

         while(itr.hasNext()){//hasNext()获取下一个元素

         String str=itr.next();//next方法得到此元素

         System.out.println(str);

         }

     }

     @Test

     public void test2() {

         List<String> ls = new ArrayList<String>();//创建List集合容器

         ls.add("北京");//向集合容器中添加元素

         ls.add("上海");

         ls.add("广东");

         ls.add("深圳");

        

         System.out.println("删除前,元素个数是:"+ls.size());

         print(ls);

        

//       ls.remove("上海"); //删除集合容器中的元素,删除“上海”这个对象

//       ls.remove(2); //删除集合容器中的元素,通过元素索引(从0开始)

        

         System.out.println(ls.isEmpty());//判断集合中是否存在元素,true=不存在;false=存在

         ls.clear(); //删除集合容器中的所有元素

        

         System.out.println("删除后,元素个数是:"+ls.size());

         print(ls);

        

         System.out.println(ls.isEmpty());//判断集合中是否存在元素,true=不存在;false=存在

     }

     private void print(List<String> list) {

         System.out.println("集合调试,输出集合中的每一个元素");

         for(String str : list) {

              System.out.println(str);

         }

     }

     /**

      * 判断一个集合中是否存在某个元素

      *true=存在;false=不存在

      */

     @Test

     public void test3() {

         List<Integer> list = new ArrayList<Integer>();

         list.add(1);

         list.add(2);

         list.add(3);

         list.add(4);

         list.add(5);      

         System.out.println(list.contains(9));

     }

     @Test

     public void test4(){

         List<Integer> list=new ArrayList<Integer>();

         for(int i=1;i<=10;i++){

              int x=i;

              list.add(x);

         }

         int totle=0;

         Iterator<Integer>itr=list.iterator();

         while(itr.hasNext()){

              int ele=itr.next();

              totle=totle+ele;

              System.out.println(ele);

         }

         System.out.println("总和为:"+totle);

     }

     @Test

     public void testt(){

         List<Integer> ts=new ArrayList<Integer>();

         for(int i=0;i<10;i++){

              int x=i;

              ts.add(x);

         }

        

         int totle=0;

         Iterator<Integer>ittor=ts.iterator();

         while(ittor.hasNext()){

              int y=ittor.next();

              System.out.println(y);

              totle=totle+y;

         }

         System.out.println("sum is"+totle);

         for(int x:ts){

              System.out.println(x);

         }

     }

List集合

List集合代表⼀个元素有序、可重复的集合,集合中每个元素都有

其对应的顺序索引。List集合允许使⽤重复元素,可以通过索引来

访问指定位置的集合元素。List集合默认按元素的添加顺序设置元

素的索引,例如第⼀次添加的元素的索引为0,第⼆次添加的元素

索引为1….以此类推

List容器中的数据对象有顺序,并且可以重复


1.add: 向List集合容器中添加元素,元素可重复添加

@Test

    public void test1(){

        List lt=newArrayList();

        lt.add("abc");      lt.add(true); //向list容器器中添加⼀一个Boolean对象

        lt.add(1); //       System.out.println(lt.toString());

    }

2. size  获取List集合容器中元素的个数

3. get  从List集合中获取元素,返回Object

4. remove(Object obj)    remove(int index) 从集合中删除元素

5 clear()  从集合中删除所有元素

6.contains(Objectobj)  集合中是否存在某个元素,返回boolean值

 7.set(int index, E obj)

将index所指定位置的元素设置为obj

@Test

    public void test1(){

        List i=newArrayList();//声明List集合容器器

        i.add("abc");//向list容器器中添加⼀一个String对象

        i.add(true); //向list容器器中添加⼀一个Boolean对象

 

        i.add(1); 向list容器器中添加⼀一个Integer对象

 

        System.out.println(i.size());//获取集合中元素的个数

        System.out.println(i.get(0));//获取集合中的元素,索引值从0开始

        i.remove("abc"); //删除集合中的元素

        i.remove(0);//删除集合中的元素,索引从0开始

        i.clear(); //删除集合中所有元素

        System.out.println(i.contains("abc"));

    }

 

 

@Test

    public void test2(){

        Student stu1 = new Student("张三", 20);

        Student stu2 = new Student("", 30);

        Student stu3 = new Student("王五", 40);

        Student stu4 = new Student("赵六", 50);

        Student stu5 = new Student("xxx", 60);

        List<Student> stus = new ArrayList<Student>();

        stus.add(stu1);// 添加学生对象

        stus.add(stu2);

        stus.add(stu3);

        stus.add(stu4);

        stus.add(stu5);

        int totle = 0;

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

            Student st = stus.get(i);

            totle += st.getAge();

        }

        System.out.println("总的年龄:" + totle);

        System.out.println("平均年龄:" + totle / stus.size());

    }

 

/**

     * 定义一个学生对象,属性:姓名(String)、分数(int),要求合理封装,重写toString方法描述学生信息

     * 定义一个集合用于存放学生对象(注意泛型的使用),存入3个学生到集合

     * 遍历集合中的元素(用标准for循环),给每个学生的分数+10分

     * 遍历集合中的元素(用foreach),输出学生信息

     */

    @Test

    public void test3() {

        List<Person> person = new ArrayList<Person>();//定义一个集合,用于存放学生对象

        Person stu1 = new Person("张三", 30);

        Person stu2 = new Person("李四", 40);

        Person stu3 = new Person("王五", 50);

       

        person.add(stu1);

        person.add(stu2);

        person.add(stu3);

        //List<Person> person = newArrayList<Person>();

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

            int score =person.get(i).getScore();

            person.get(i).setScore(score+10);

        }

       

       

        for(Person stu : person) {

            System.out.println(stu.toString());

        }

    }

@Test

     public void test5() {

         List<News> news = new ArrayList<News>();

         News news1 = new News("中国多地遭雾霾笼罩空气质量再成热议话题");

         News news2 = new News("春节临近北京“卖房热”");       

         news.add(news1);

         news.add(news2);

        

         Iterator<News> itr =news.iterator();

    

         while(itr.hasNext()) {

              News totlenews = itr.next();

              String title = totlenews.getTitle();

              if(title.length() >= 15) {

                   title = title.substring(0,14)+"...";

              }

              totlenews.setTitle(title);

              System.out.println(totlenews);

         }   

     }   

Set集合唯一性,无序性

Set集合类似于⼀个罐⼦,程序可以把多个元素扔进罐⼦⾥,⽽Set

集合不能记住元素添加的顺序;Set集合中不允许保存相同的对象

Set容器中的数据对象没有顺序,并且不可重复

HashSet提供的常⽤⽅法:

1.add 

2.size 

3.iterator() 

@Test

public void test2(){

User user1 = new User("张三", 18);

iterator()

迭代器获取Set集合中所有的元素

HashSet提供的常⽤⽅

Set

Set容器中的数据对象没有顺序,并且不可重复

Collection容器

Collection定义了存取组对象的法,其Set和List分别定义了存储

集合框架(容器)

User user1 = new User("张三", 18);

User user2 = new User("", 20);

Set set = new HashSet(); //创建Set集合容器

set.add(user1); //添加元素到集合

set.add(user2); //添加元素到集合

Iterator itr = set.iterator(); //创建迭代器

while(itr.hasNext()){ //如果set中还有元素可以迭代,就继续查找下一个元素

User u = (User) itr.next(); //获取迭代的元素对象

System.out.println(u.toString());

}

}

4.remove

 5. clear()

 6.contains(Objectobj)

//Set集合无序性,唯一性。

      @Test

      public void test5() {

           Set<String> cities = new HashSet<String>();//创建Set集合对象

          

           cities.add("北京");//向set集合中添加元素

           cities.add("上海");

           cities.add("上海");

           cities.add("广东");

           cities.add("广东");

           cities.add("广东");

           cities.add("深圳");

          

           /**

            * 通过forEach遍历set集合

            */

           for(String city : cities) {

                 System.out.println(city);

           }

      }

     

      /**

       * 生成一个6位数的序列号,要求序列号中不能有重复的数字

       */

      @Test

      public void test6() {

           Set<Integer> set = new HashSet<Integer>();

           while(set.size()<=5) {

                 int i = (int)(Math.random()*10);

                 set.add(i);

                 System.out.println("随机数"+i);

           }

           String sn = "";

           for(int i : set) {

                 sn += i;

           }

           System.out.println(sn);

          

      }

 

@Test

      public void test2(){

           Set<Integer> set=new HashSet<Integer>();

           set.add(1);

           set.add(4);

           set.add(3);

           System.out.println(set.size());

           /*Iterator<Integer> itr=set.iterator();

           while(itr.hasNext()){

                 Integer i = itr.next();

                 System.out.println(i);

           }*/

      }    

      @Test

      public void test3(){

           Set<Integer> set=new HashSet<Integer>();

           while(true){

                 int x=(int)(Math.random()*10);

                 System.out.println(x);

                 if(set.size()<5){

                       set.add(x);

                 }else{

                      break;

                 }

           }

           System.out.println(set.toString());

      }

Map集合字典)Map容器定义了储存“键(key)——值(value)映射对”的⽅法,简称“键值对”

Map⽤于保存具有映射关系的数据,因此Map集合⾥保存着两组

值,⼀组值⽤于保存Map⾥的key,另外⼀组值⽤于保存Map⾥的

value,key和value都可以是任何引⽤类型的数据。Map的key不允

许重复;key和value之间存在单项⼀对⼀关系,即通过指定的

key,总能找到唯⼀的、确定的value。从Map中取出数据时,只要

给出指定的key,就可以取出对应的value

 

@Test

      public void test1() {

           Map<String, String> map = new HashMap<String, String>();//定义Map集合(字典)

           map.put("2210", "沈阳市"); //向Map集合中添加元素

           map.put("7910", "西安市");

           map.put("2410", "长春市");

     

//         System.out.println(map.containsKey("2210"));//在map集合中查找对应的key,true=找到了

//         System.out.println(map.containsValue("沈阳市")); //在map集合中查找对应的value,true=找到了

//         map.clear(); //清空map集合中的所有元素

//         System.out.println(map.isEmpty()); //判断map集合中是否存在元素,true=不存在

//         map.remove("2210"); //从map集合中删除记录

//         System.out.println(map.get("2210"));//在map集合中根据key找到对应的value,找到了返回value的值,找不到返回null

//         System.out.println(map.size()); //获得map集合的记录条数

          

           /**

            * 通过keySet遍历map集合

            */

           Set<String> ks = map.keySet();

           for(String k : ks) {

                 System.out.println("key="+k);

                 System.out.println("value="+map.get(k));

           }

          

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

          

           /**

            * 通过Entry对象遍历map集合

            */

           Set<Entry<String,String>> entrySet = map.entrySet();

           for(Entry<String, String> en : entrySet) {

                 if(en.getKey().equals("2410")) {

                      en.setValue("上海市");//给记录设置value

                 }

                 System.out.println("key="+en.getKey());//获取Entry对象的key值

                 System.out.println("value="+en.getValue());//获取Entry对象的value值

           }

      }

@Test

      public void test4(){

           Map<String,String> map=new HashMap<String, String>();

           map.put("no1", "bj");

           map.put("no2", "sh");

           map.put("no3", "gz");

           map.put("no4", null);

           map.put(null,"bj");

           System.out.println(map.get("no1"));

           Set<String> set=map.keySet();

           Iterator<String>ks=set.iterator();

           while(ks.hasNext()){

                 String key = ks.next();

                 String value = map.get(key);

                 System.out.println(key+value);

           }

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

           for(String key:set){//Set<String> set=map.keySet();

                 String value=map.get(key);

                 System.out.println(key+value);

           }

      }

     

      @Test

      public void test5(){

           Map<String,String> map=new HashMap<String, String>();

           map.put("no1", "bj");

           map.put("no2", "sh");

           map.put("no3", "gz");

           map.put("no4", null);

           map.put(null,"bj");

           Set<Entry<String,String>> set=map.entrySet();

           Iterator<Entry<String,String>> ks=set.iterator();

           while(ks.hasNext()){

                 Entry<String, String> ey= ks.next();

                 String key = ey.getKey();

                 String value = ey.getValue();

                 System.out.println(key+value);

           }

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

           for(Entry<String, String> en:set){//Set<Entry<String, String>>set=map.entrySet();

                 System.out.println(en.getKey()+en.getValue());

           }

      }

Map提供的常⽤⽅法:

put(Object key, Object value)

向Map集合中添加条记录,记录是以键值对的形式存放的

Object get(Object key)

从Map集合中通过key来获取value

 

Set keySet()

获取map集合中所有的key

 

Set entrySet()

获取Map集合中所有的记录(key-value对象Entry)

 

Collections具类:

集合⼯具类,针对于Set和List集合提供⼀系列功能的操作

1.sort(Collectionc)

按照⾃然顺序升序排序

 

2.Object max(Collection c)

获取c集合容器中的最⼤值

 

3.Object min(Collection c)

获取c集合容器中的最⼩值

 

4.boolean replaceAll(Collection c, Object oldVal, Object newVale)

将c容器中的oldVal替换成newVal

     

@Test

      public void test6(){

           List<Integer> list=new ArrayList<Integer>();

           list.add(7);

           list.add(45);

           list.add(23);

           list.add(78);

           System.out.println(list.toString());

           Collections.sort(list);

           System.out.println(list.toString());

           System.out.println(Collections.max(list));

           System.out.println(Collections.min(list));

           Collections.replaceAll(list, 45, 888);

           System.out.println(list.toString());

      }

案例:给对象进⾏排序

⽤户类中包含姓名和年龄属性,要求给多个⽤户按照年龄进⾏

排序

 

packaget3;

publicclass User implements Comparable<User>{

privateString name;

privateint age;

@Override

public int compareTo(User o) {

if(this.age > o.getAge()) {

return1;

}else{

return-1;

}

}

publicUser(String name, int age) {

this.name= name;

this.age= age;

}

publicString getName() {

returnname;

}

publicvoid setName(String name) {

this.name= name;

}

publicint getAge() {

returnage;

}

publicvoid setAge(int age) {

this.age= age;

}

}

2、在测试类中调⽤Collections集合的sort⽅法对集合进⾏排

List<User>list = new ArrayList<User>();

list.add(newUser(“张三”,89));

list.add(newUser(“李四”, 66));

list.add(newUser(“王五”,90));

list.add(newUser(“赵六”,12));

Collections.sort(list);//对⽤用户集合进⾏行行排序

泛型

泛型是指“类型参数化”,使⽤泛型可以屏蔽程序在运⾏时的类型

转换异常,减少强制类型转换的使⽤,并且可以让异常在编译期

暴露出来

 

E set(int index, E obj)

将index所指定位置的元素设置为obj

E get(int index)

返回指定索引处存储的对象

E set(int index, E obj)

将index所指定位置的元素设置为obj

E get(int index)

返回指定索引处存储的对象

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值