Java collection framework map

Title: Java collection framework map date: 2017-08-09 14:38:12 Tags: Collection framework categories: - Java

public class MapDemo01 {
    public static void main(String[] args) {
        HashMap<String,String> hashMap=new HashMap<>();
        //当第一次存放元素的时候这个键不存在所以返回的是null
        //第二次再存放同一个键的值的时候不会报错而是返回的改建原有的值这个和Set以及collection是不一样的
        System.out.println(hashMap.put("01","zhansgan01"));
        System.out.println(hashMap.put("01","zhansgan02"));
        hashMap.put("03","zhansgan03");
        hashMap.put("04","zhansgan04");

        System.out.println(hashMap.get("01"));
        Collection<String> collection=hashMap.values();
        System.out.println(collection);

        System.out.println(hashMap.containsKey("02"));
        System.out.println(hashMap.containsValue("zhansgan03"));
        //remove返回的value
        System.out.println(hashMap.remove("03"));
    }
}

3. Three commonly used younger brothers of map:

4. The two particularly important functions keyset and entryset are keyset. In fact, the structure in the map set is a double column structure, that is; It is composed of two sets, which store the references of key values respectively. The keyset only takes out the keys, which is similar to values. When all the keys are taken out, it means that we have all the values. At this time, we can traverse the map. The map itself has no traversal method

  public class KeyMapDemo {
      public static void main(String[] args) {
          HashMap<String,String> hashMap=new HashMap<>();
          hashMap.put("1","zs1");
          hashMap.put("2","zs2");
          hashMap.put("3","zs3");
          hashMap.put("4","zs4");
          Set<String> keySet =hashMap.keySet();
          Iterator<String> it=keySet.iterator();
          for (;it.hasNext();){
              String key=it.next();
              System.out.println(hashMap.get(key));
          }

      }
  }

5. Entryset directly returns the mapping relationship of the map, which is only a relationship rather than a tuple. The type of this relationship is map There are getValue and getKey methods in the entry type. Entry is actually the internal interface of the map interface, just like the internal class. This is the internal interface and this interface is static

  public class EntrySet {
      public static void main(String[] args) {
          Map<String,String> map=new HashMap<>();
          map.put("1","s1");
          map.put("2","s2");
          map.put("3","s3");
          //返回的还是set集合只里面的类型是Map.Entry类型的
          Set<Map.Entry<String,String>> mapEntry=map.entrySet();
          for (Map.Entry me :
                  mapEntry) {
              System.out.println(me.getKey()+"--------"+me.getValue());
          }
      }
  }

  //类似于种东西
  interface Map{
      static interface Entry{
          abstract Object getKey();
          abstract Object getValue();
      }
  }

5. A small demo

   /**
    * Created by lwen on 2017/7/13.
    * 把一个字符串里面的字符的数目统计一下,,并且按照字符的顺序显示
    */
   public class MapDemo03 {
       public static void main(String[] args) {
           String str=charCount("aasdfasadcl");
           System.out.println(str);
       }

       static String charCount(String str){
           char[] chs=str.tocharArray();
           TreeMap<Character,Integer> treeMap=new TreeMap<>();
           int count=0;
           for (char ch:chs){
               if (treeMap.get(ch)!=null){
                   count=treeMap.get(ch);
               }
               count++;
               treeMap.put(ch,count);
               count=0;
           }
           StringBuilder sb=new StringBuilder();
           Set<Map.Entry<Character,Integer>> set=treeMap.entrySet();
           for (Map.Entry<Character,Integer> em:set){
               sb.append(em.getKey()).append("(").append(em.getValue()).append(")");
           }
           return sb.toString();
       }

   }

7. There are two major parts of the collective framework, namely:

    ---Collection
        |--List  ArrayList LinkedList
        |--Set  HashSet  TreeSet
    ---Map
        |--HashTable
        |--HashMap
        |--TreeMap

In addition, there are two commonly used classes: collections, which provides:

Another tool class is arrays. The methods in this class are mainly used to operate arrays:

    class StrLenComparator implements Comparator<String>{
        public int compare(String s1,String s2){
            if (s1.length()>s2.length()){
                return 1;
            }else if(s1.length()<s2.length()){
                return -1;
            }
            return s1.compareTo(s2);
        }
    }

    public class CollectionsDemo {
        public static void main(String[] args) {
            List<String> list=new ArrayList<>();
            list.add("aaa");
            list.add("ab");
            list.add("adc");
            list.add("dd");
            list.add("cd");
            list.add("efcasdc");
            Collections.sort(list);
            for (String string:list){
                System.out.println(string);
            }

            Collections.sort(list,new StrLenComparator());
            for (String string:list){
                System.out.println(string);
            }
        }
    }

10. Static import: when we import a package, we import the classes in the package. When we use static import, import static imports all static members of the class, whether properties or methods

import static java.util.Arrays.*;
import static java.util.Collections.*;

public class StaticImport {
  public static void main(String[] args) {
      int[] arr=new int[11];
      for (int i=10,j=0;i>0;i--,j++){
          arr[j]=i;
      }
      sort(arr);   //可以直接使用Arrays中的方法而不用写Arrays.sort但是如果同一个类中名字冲突的话需要加上
      for (int ele:arr){
          System.out.println(ele);
      }
  }
}

9. Differences between HashMap and hashtable: 1) HashMap is not thread synchronized, while hashtable is thread synchronized, that is, the former is more efficient, while the latter is less efficient and has the opposite security. 2) HashMap is a subclass of map. Hashtable is a subclass of dictionary 3) the key values of HashMap can be null, and the key values of hashtable can not be null 10 Use of hashtable. Generally speaking, hashtable is rarely used. There is also a commonly used subclass, the properties class of hashtable. This class is mainly used to read, write and load configuration files. Only strings are allowed in this container. No matter the key values, the stored key values can be converted into ordinary configuration files or XML files, Then you can use load to load next time

public class HashTableDemo {
    public static void main(String[] args) throws IOException{
        Properties properties=new Properties();
        properties.setProperty("user","lwen");
        properties.setProperty("pwd","123");
        properties.store(new FileWriter("info.properties"),"用户配置文件");
        properties.store(new FileOutputStream("info_1.properties"),"用户配置文件");  //可以字符流也可以字节流
        properties.storeToXML(new FileOutputStream("info.xml"),"xml");  //这个只能使用字节流对象  xml没有编码
        System.out.println(properties.getProperty("user","not this "));  //如果找不到这个属性,则会返回默认值
        properties.load(new FileReader("info.properties"));  //加载配置文件是直接加载到这个对象里面,而不是打印


    }
}

11. Variables in memory are generally divided into four types, which are different for the garbage collection mechanism: strong reference: they will not be recycled by GC at any time; soft reference: they may be recycled by GC, and will only be recycled when the JVM memory is insufficient; weak reference: they will be recycled when GC is running: similar to no reference, It mainly tracks the recycled status of objects and cannot be used alone. It is generally used together with the reference queue. Here we focus on strong and weak references. The so-called strong references are generally string constants that reside in memory for sharing for a long time. When we store a lot of content in a HashMap, sometimes we need to clear some useless data, We can run GC, so the weakhashmap is born. In this way, the weak types in it will be killed

public class WeakHashMapDemo {
    public static void main(String[] args) {
        WeakHashMap<String,String> weakHashMap=new WeakHashMap<>();
        //这两个事在常量池中的常量,所以放到weakmap中也不会被gc
        weakHashMap.put("zhangsan0","122");
        weakHashMap.put("zhangsan1","123");
        //这两个则是两个对象在堆内存中,放到这里了以后,肯定被gc
        weakHashMap.put(new String("zhangsan2"),"102");
        weakHashMap.put(new String("zhangsan3"),"1245");
        //运行垃圾回收机制之前
        Set<Map.Entry<String,String>> me=weakHashMap.entrySet();
        for (Map.Entry<String,String> stringStringEntry : me) {
            System.out.println(stringStringEntry.getKey());
            System.out.println(stringStringEntry.getValue());
        }

        //运行垃圾回收机制
        System.gc();
        System.runFinalization();

        //垃圾回收之后
        System.out.println("=========================");
        Set<Map.Entry<String,String>> me1=weakHashMap.entrySet();
        for (Map.Entry<String,String> stringStringEntry : me1) {
            System.out.println(stringStringEntry.getKey());
            System.out.println(stringStringEntry.getValue());
        }
    }
}

12. The container of identityhashmap takes the address of the key as the comparison object. Note that it is the address rather than others. For example, if it is a string constant, it is obvious that this will be repeated as long as the content is the same. If it is a string object, it is different address values, even if their content is the same

public class IdentifiedHashMapDemo {
    public static void main(String[] args) {
        IdentityHashMap identityHashMap=new IdentityHashMap();
        //前两个是字符串常量,在常量池中,地址是一样的
        identityHashMap.put("a","21");
        identityHashMap.put("a","22");
        //后面两个是不同的对象,因此他们都被存入
        identityHashMap.put(new String("a"),"23");
        identityHashMap.put(new String("a"),"24");
        System.out.println(identityHashMap.size());
    }
}

13. When multithreading is encountered in the collection framework and we need to use those asynchronous collections, we must manually synchronize these collections, and we also need to add some restrictions when we want the collection to be immutable

public class SyncDemo {
    public static void main(String[] args) {
        List<String> list=new ArrayList<>();
        List<String> list1=Collections.synchronizedList(list);
//        这样一来list1就是一个同步的arraylist
//        其他的几个容器类似
        List<String> list2=Collections.unmodifiableList(list1);
        //这样一来list2就是一个不可修改的容器也就是此时的容器不再支持增删操作

    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>