集合(二)

本文详细介绍了Java泛型的应用及其如何解决类型安全问题,并深入探讨了Map集合的使用方法,包括添加、删除、判断及获取等操作,以及两种取出方式。此外,还提供了具体的代码示例帮助读者更好地理解和掌握。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

泛型的高级应用

JDK1.5版本以后出现的新特性,用于解决安全问题,是一个类型安全机制。

优点:

1·将运行时期出现的问题classCaseException转移到了编译时期,方便程序员解决问题,

   让运行时期问题减少,更加安全。

2·避免了强制类型转换的麻烦。

泛型类:

什么时候定义泛型类?

   当类中操作的引用数据类型不确定的时候,

   早期定义Object来完成扩展,现在定义泛型来完成扩展。

  • 泛型类定义的类型,在整个类中有效,如果被方法调用,那么泛型类的对象明确要操作的具体类型后,
        所有要操作的类型就已经固定了。
  • 为了让不同方法可以操作不同类型,而类型还不确定,那么可以将泛型定义在方法上。
  • 特殊之处:
      静态方法不可以访问类上定义的泛型
      如果静态方法操作的引用数据类型不确定时,可以将泛型定义在方法上,跟类上的泛型类型不同。

泛型可以定义在接口上.

import java.util.*;  
class GenericDemo6  
{  
         publicstatic void main(String[] args)  
         {  
                    
   
                   ArrayList<Person> al = new ArrayList<Person>();  
                   al.add(new Person("abc1"));  
                   al.add(new Person("abc2"));  
                   al.add(new Person("abc3"));  
                   //printColl(al);  
   
                   ArrayList<Student> al1 = new ArrayList<Student>();  
                   al1.add(new Student("abc--1"));  
                   al1.add(new Student("abc--2"));  
                   al1.add(new Student("abc--3"));  
                   printColl(al1);  //ArrayList<? extends Person> al = newArrayList<Student>();error  
   
         }  
         publicstatic void printColl(Collection<? extends Person> al)  
         {  
                   Iterator<?extends Person> it = al.iterator();  
   
   
                   while(it.hasNext())  
                   {  
                            System.out.println(it.next().getName());  
                   }  
         }  
         /* 
         public static void printColl(ArrayList<?> al)//ArrayList al = newArrayList<Integer>();error 
         { 
                   Iterator<?> it = al.iterator(); 
  
  
                   while(it.hasNext()) 
                   { 
                            System.out.println(it.next().toString()); 
                   } 
         } 
         */  
}  
   
class Person  
{  
         private String name;  
         Person(Stringname)  
         {  
                   this.name= name;  
         }  
         public String getName()  
         {  
                   return name;  
         }  
}  
   
class Student extends Person  
{  
         Student(Stringname)  
         {  
                   super(name);  
         }  
   
}  


通配符,也可以理解为占位符。

泛型的限定:适用于泛型扩展用的

  1. ? extends E: 可以接收E类型或者E的子类型。上限。
  2. ? super E: 可以接收E类型或者E的父类型。下限

import java.util.*;  
class GenericDemo7  
{  
         public static void main(String[] args)  
         {  
                    
                   TreeSet<Student> ts = new TreeSet<Student>(new Comp());  
   
                   ts.add(new Student("abc03"));  
                   ts.add(new Student("abc02"));  
                   ts.add(new Student("abc06"));  
                   ts.add(new Student("abc01"));  
                    
                   Iterator<Student> it = ts.iterator();  
   
                   while(it.hasNext())  
                   {  
                            System.out.println(it.next().getName());  
                   }  
                   /**/  
   
   
   
                   TreeSet<Worker> ts1 = new TreeSet<Worker>(new Comp());  
   
                   ts1.add(new Worker("wabc--03"));  
                   ts1.add(new Worker("wabc--02"));  
                   ts1.add(new Worker("wabc--06"));  
                   ts1.add(new Worker("wabc--01"));  
   
   
                   Iterator<Worker> it1 = ts1.iterator();  
   
                   while(it1.hasNext())  
                   {  
                            System.out.println(it1.next().getName());  
                   }  
         }  
}  
   
/* 
class StuComp implements Comparator<Student> 
{ 
         public int compare(Student s1,Student s2) 
         { 
                   return s1.getName().compareTo(s2.getName()); 
         } 
} 
  
class WorkerComp implementsComparator<Worker> 
{ 
         public int compare(Worker s1,Worker s2) 
         { 
                   return s1.getName().compareTo(s2.getName()); 
         } 
} 
*/  
   
class Comp implementsComparator<Person>  
{  
         public int compare(Person p1,Person p2)  
         {  
                   return p2.getName().compareTo(p1.getName());  
         }  
}  
   
   
class Person  
{  
         private String name;  
         Person(Stringname)  
         {  
                   this.name= name;  
         }  
         public String getName()  
         {  
                   return name;  
         }  
         public String toString()  
         {  
                   return "person :"+name;  
         }  
}  
   
class Student extends Person  
{  
         Student(Stringname)  
         {  
                   super(name);  
         }  
   
}  
   
class Worker extends Person  
{  
         Worker(Stringname)  
         {  
                   super(name);  
         }  
}  

Map集合:

该集合存储键值对。一对一对往里存。而且要保证键的唯一性。

         1,添加。

                   put(Kkey, V value)

                   putAll(Map<?extends K,? extends V> m)

         2,删除。

                   clear()

                   remove(Objectkey)

         3,判断。

                   containsValue(Objectvalue)

                   containsKey(Objectkey)

                   isEmpty()

         4,获取。

                   get(Objectkey)

                   size()

                   values()

                   entrySet()

                   keySet()

Map

         |--Hashtable:底层是哈希表数据结构,不可以存入null键null值。该集合是线程同步的。jdk1.0.效率低。

         |--HashMap:底层是哈希表数据结构,允许使用 null 值和 null 键,该集合是不同步的。将hashtable替                                     代,jdk1.2.效率高。

         |--TreeMap:底层是二叉树数据结构。线程不同步。可以用于给map集合中的键进行排序。

和Set很像,Set底层就是使用了Map集合。

import java.util.*;  
class MapDemo  
{  
         publicstatic void main(String[] args)  
         {  
                   Map<String,String> map = new HashMap<String,String>();  
   
                   //添加元素,添加元素,如果出现添加时,相同的键。那么后添加的值会覆盖原有键对应值。  
                   //并put方法会返回被覆盖的值。  
                   System.out.println("put:"+map.put("01","zhangsan1"));  
                   System.out.println("put:"+map.put("01","wnagwu"));  
                   map.put("02","zhangsan2");  
                   map.put("03","zhangsan3");  
   
                   System.out.println("containsKey:"+map.containsKey("022"));  
                   //System.out.println("remove:"+map.remove("02"));  
   
                   System.out.println("get:"+map.get("023"));  
   
                   map.put("04",null);  
                   System.out.println("get:"+map.get("04"));  
                   //可以通过get方法的返回值来判断一个键是否存在。通过返回null来判断。  
   
                    
                   //获取map集合中所有的值。  
                   Collection<String> coll = map.values();  
   
                   System.out.println(coll);  
                   System.out.println(map);  
         }  
}  

Map集合的两种取出方式:

1,Set<k> keySet:将map中所有的键存入到Set集合。因为set具备迭代器。

         所有可以迭代方式取出所有的键,在根据get方法。获取每一个键对应的值。

2,Set<Map.Entry<k,v>> entrySet:将map集合中的映射关系存入到了set集合中,

     而这个关系的数据类型就是:Map.Entry

     Entry其实就是Map中的一个static内部接口。

为什么要定义在内部呢?

   因为只有有了Map集合,有了键值对,才会有键值的映射关系。

   关系属于Map集合中的一个内部事物。

   而且该事物在直接访问Map集合中的元素

import java.util.*;  
class MapDemo2  
{  
         publicstatic void main(String[] args)  
         {  
                   Map<String,String>map = new HashMap<String,String>();  
   
                   map.put("02","zhangsan2");  
                   map.put("03","zhangsan3");  
                   map.put("01","zhangsan1");  
                   map.put("04","zhangsan4");  
                    
                   //第二种方法  
                   //将Map集合中的映射关系取出。存入到Set集合中。  
                   Set<Map.Entry<String,String>>entrySet = map.entrySet();  
   
                   Iterator<Map.Entry<String,String>>it = entrySet.iterator();  
   
                   while(it.hasNext())  
                   {  
                            Map.Entry<String,String>me = it.next();  
                            Stringkey = me.getKey();  
                            Stringvalue = me.getValue();  
   
                            System.out.println(key+":"+value);  
   
                   }  
   
                   /* 
//第一种方法 
                   //先获取map集合的所有键的Set集合,keySet(); 
                   Set<String> keySet = map.keySet(); 
  
                   //有了Set集合。就可以获取其迭代器。 
                   Iterator<String> it = keySet.iterator(); 
  
                   while(it.hasNext()) 
                   { 
                            String key = it.next(); 
                            //有了键可以通过map集合的get方法获取其对应的值。 
                            String value  = map.get(key); 
                            System.out.println("key:"+key+",value:"+value); 
                   } 
  
                   */  
   
         }  
}  
   
/* 
Map.Entry 其实Entry也是一个接口,它是Map接口中的一个内部接口。 
  
interface Map 
{ 
         publicstatic interface Entry 
         { 
                   public abstract Object getKey(); 
                   public abstract Object getValue(); 
  
         } 
} 
  
class HashMap implements Map 
{ 
         class Hahs implements Map.Entry 
         { 
                   public  Object getKey(){} 
                   public  Object getValue(){} 
         } 
         
} 
*/  

练习:

/* 
需求:对学生对象的年龄进行升序排序。 
  
因为数据是以键值对形式存在的。 
所以要使用可以排序的Map集合。TreeMap。 
*/  
import java.util.*;  
   
class StuNameComparator implementsComparator<Student>  
{  
         public int compare(Student s1,Student s2)  
         {  
                   int num = s1.getName().compareTo(s2.getName());  
                   if(num==0)  
                            return new Integer(s1.getAge()).compareTo(new Integer(s2.getAge()));  
   
                   return num;  
         }  
}  
   
   
class MapTest2  
{  
         public static void main(String[] args)  
         {  
                   TreeMap<Student,String> tm = new TreeMap<Student,String>(new StuNameComparator());  
   
                   tm.put(new Student("blisi3",23),"nanjing");  
                   tm.put(new Student("lisi1",21),"beijing");  
                   tm.put(new Student("alisi4",24),"wuhan");  
                   tm.put(new Student("lisi1",21),"tianjin");  
                   tm.put(new Student("lisi2",22),"shanghai");  
   
                    
                   Set<Map.Entry<Student,String>> entrySet = tm.entrySet();  
   
                   Iterator<Map.Entry<Student,String>> it = entrySet.iterator();  
   
                   while(it.hasNext())  
                   {  
                            Map.Entry<Student,String> me = it.next();  
   
                            Student stu = me.getKey();  
                            String addr = me.getValue();  
                            System.out.println(stu+":::"+addr);  
                   }  
         }  
}  

集合嵌套:

import java.util.*;  
class MapDemo3  
{  
         publicstatic void main(String[] args)  
         {  
                   Map<String,HashMap<String,String>> czbk = new HashMap<String,HashMap<String,String>>();  
   
                   HashMap<String,String> yure = new HashMap<String,String>();  
                   HashMap<String,String> jiuye = new HashMap<String,String>();  
   
                   czbk.put("yure",yure);  
                   czbk.put("jiuye",jiuye);  
   
                   yure.put("01","zhangsan");  
                   yure.put("02","lisi");  
   
                   jiuye.put("01","wangwu");  
                   jiuye.put("02","zhouqi");  
   
                   Iterator<String> it = czbk.keySet().iterator();  
                   while(it.hasNext())  
                   {  
                            String id = it.next();  
                            HashMap<String,String> room = czbk.get(id);  
                            System.out.println(id);  
                            getInstance(room);  
                   }  
         }  
         publicstatic void getInstance(HashMap<String,String> room)  
         {  
                   Iterator<String> it = room.keySet().iterator();  
                  while(it.hasNext())  
                   {  
                            String id = it.next();  
                            String name = room.get(id);  
                            System.out.println(id+"..."+name);  
                   }  
         }  
}  
/* 
  
第二种(“01”,”zhangsan”)属于Student类 
map扩展知识。 
map集合被使用是因为具备映射关系。 
  
"yureban" Student("01""zhangsan"); 
  
"yureban" Student("02""lisi"); 
  
"jiuyeban" "01""wangwu"; 
"jiuyeban" "02""zhaoliu"; 
  
一个学校有多个教室。每一个教室都有名称。 
*/  
import java.util.*;  
   
class Student  
{  
         private String id;  
         private String name;  
         Student(Stringid,String name)  
         {  
                   this.id= id;  
                   this.name= name;  
         }  
   
         public String toString()  
         {  
                   return id+"..."+name;  
         }  
}  
   
   
class MapDemo3  
{  
         public static void main(String[] args)  
         {  
                   Map<String,List<Student>> czbk = new HashMap<String,List<Student>>();  
   
                   List<Student> yure = new ArrayList<Student>();  
                   List<Student> jiuye = new ArrayList<Student>();  
   
                   czbk.put("yure",yure);  
                   czbk.put("jiuye",jiuye);  
                    
                   yure.add(new Student("01","zhangsan"));  
                   yure.add(new Student("02","lisi"));  
   
                   jiuye.add(new Student("03","wangwu"));  
                   jiuye.add(new Student("04","zhaoliu"));  
   
                   Iterator<String> cz = czbk.keySet().iterator();  
   
                   while(cz.hasNext())  
                   {  
                            String id= cz.next();  
                            List<Student> room = czbk.get(id);  
                            System.out.println(id);  
                            getIntance(room);  
   
                   }  
         }  
          
                   publicstatic void getIntance(List<Student> room)  
                   {  
                            Iterator<Student> it = room.iterator();  
                            while(it.hasNext())  
                            {  
                                     Student s = it.next();  
                                     System.out.println(s);  
                            }  
                   }  
   
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值