Understanding different sets in JAVA

Keywords: Java Android JDK Eclipse

Today, after searching the Internet, I found a blog about java collections, which is very well organized. I intentionally copied it to share with you

In this lecture: Collection collection

Before we talk about collection, let's distinguish three concepts:

colection set, used to represent any kind of data structure
Collection collection interface, referring to the java.util.Collection interface, is a superclass interface for Set, List, and Queue interfaces
Collections collection tool class, refers to the java.util.Collections class.

The SCJP exam requires that you know the following interfaces: Collection, Set, SortedSet, List, Map, SortedMap, Queue, NavigableSet, NavigableMap, and an Iterator interface.

The classes required for the SCJP exam are HashMap, Hashtable, TreeMap, LinkedHashMap, HashSet, LinkedHashSet, TreeSet, ArrayList, Vector, LinkedList, PriorityQueuee, Collections, Arrays

The following is a diagram of the relationship between a set:

ArrayList and HashMap with bold lines in the figure above are our main points.The image below looks more hierarchical.

Collections are lower-case collections, and there are four basic forms of collections, of which the first three parent interfaces are Collections.

List Index List of Things to Focus on
Set focuses on the uniqueness of things
Queue focuses on the order in which things are processed
Map focuses on the mapping of things and the uniqueness of key values

1. Collection interface

The Collection interface is the parent of the Set, List, and Queue interfaces and provides method declarations commonly used by most collections, including add(), remove(), contains(), size(), iterator(), and so on.

Add(E) Adds the specified object to the collection
remove(Object o) removes the specified object from the collection, returns true successfully, false unsuccessfully
contains(Object o) to see if the collection contains the specified object, including the return true, not the return flase
size() returns the number of objects stored in the collection.Return value is int
clear() removes all objects in the collection and empties the collection.
iterator() returns an iterator object that contains all objects and is used to iterate through them
toArray() returns an array of all objects of type Object
toArray(T[] t) returns an array of the specified type containing all objects

Here's just one example of turning a collection into an array, because Collection itself is an interface, so we use its implementation class, ArrayList, to do this:

01  import java.util.ArrayList;
02  import java.util.Collection;
03   
04  public class CollectionTest {
05   
06      public static void main(String[] args) {
07   
08          String a = "a",b="b",c="c";
09          Collection list = new ArrayList();
10          list.add(a);
11          list.add(b);
12          list.add(c);
13   
14          String[] array =  list.toArray(new String[1]);
15   
16          for(String s : array){
17              System.out.println(s);
18          }
19      }
20  }

Compile and run the program to check the results:

2. Introduction to Several Important Interfaces and Classes

1. List interface

Lists are concerned with indexes, and what makes Lists unique to other collections is some of the methods associated with indexes: get(int index), add(int index,Object o), indexOf(Object o).

ArrayList can be interpreted as a growing array that provides the ability to iterate quickly and access randomly quickly.

The elements in a LinkedList are double-linked, and LinkedList is the only choice in a List when fast insertion and deletion are required.

Vector is a thread-safe version of ArrayList that has lower performance than ArrayList and is now rarely used

2. Set interface

Set cares about uniqueness, it does not allow duplication.

HashSet can be used when you don't want duplicate values in a collection and don't care about the order between elements.

LinkedHashset can be used when you do not want duplicate values in a collection and you want to iterate through elements in the order they are inserted.

TreeSet can be used when you do not want duplicate values in a collection and want to sort elements in their natural order.(Natural order means a sort that has nothing to do with the insertion order but with the content and nature of the element itself, for example,'abc'comes before'abd'.)

3. Queue interface

Queue is used to save the list of tasks to be performed.

LinkedList also implements the Queue interface, which implements a FIFO queue.

PriorityQueue is used to create a naturally ordered priority queue.There is an example in Fanwai's story http://android.yaohuiji.com/archives/3454 You can have a look.

4. Map interface

Map is concerned with unique identifiers.He maps a unique key to an element.Of course, both keys and values are objects.

HashMap can be used when a key-value pair representation is required, regardless of the order.

Hashtable notices that t is lowercase in Hashtable, a thread-safe version of HashMap that is now rarely used.

LinkedHashMap can be used when a key-value pair is needed and when the insertion order is concerned.

TreeMap can be used when a key-value pair is needed and care about the natural ordering of elements.

3. Use of ArrayList

ArrayList is a variable-length array implementation that is very efficient to read and is the most commonly used collection type.

1. Creation of ArrayList

Prior to Java 5 we used:

1   List list = new ArrayList();

After the Java 5 release, we used generic writing:

1   List<String> list = new ArrayList<String>();

The code above defines a list that allows only strings to be saved, and the type enclosed in angle brackets is the parameter type, which is also generic.Writing with generics gives us a type-safe collection.Knowledge of generics can be found here.

2. Use of ArrayList:

01  List<String> list = new ArrayList<String>();
02  list.add("nihao!");
03  list.add("hi!");
04  list.add("konikiwa!");
05  list.add("hola");
06  list.add("Bonjour");
07  System.out.println(list.size());
08  System.out.println(list.contains(21));
09  System.out.println(list.remove("hi!"));
10  System.out.println(list.size());

For methods in the List interface and methods in ArrayList, you can see the help in JDK.

3. Automatic boxing of basic data types:

We know that collections contain objects, not basic data types. After Java5, we can use auto-boxing to import basic data types more easily.

1 List list = new ArrayList();
2 list.add(new Integer(42));
3 list.add(43);
4. ArrayList sorting:

The ArrayList itself does not have sorting capabilities, but we can use the sort method of the Collections class to sort it.Let's look at an example:

01  import java.util.ArrayList;
02  import java.util.Collections;
03  import java.util.List;
04   
05  public class Test {
06   
07      public static void main(String[] args) {
08          List<String> list = new ArrayList<String>();
09          list.add("nihao!");
10          list.add("hi!");
11          list.add("konikiwa!");
12          list.add("hola");
13          list.add("Bonjour");
14   
15          System.out.println("Before sorting:"+ list);
16   
17          Collections.sort(list);
18   
19          System.out.println("After sorting:"+ list);
20      }
21   
22  }

Compile and run the program to see the results:

Before sorting: [nihao!, hi!, konikiwa!, hola, Bonjour]

After sorting: [Bonjour, hi!, hola, konikiwa!, nihao!]

5. Conversion between Array and List

To convert from an array to a list, you can use the asList() method of the Arrays class:

01  import java.util.ArrayList;
02  import java.util.Collections;
03  import java.util.List;
04   
05  public class Test {
06   
07      public static void main(String[] args) {
08   
09              String[] sa = {"one","two","three","four"};
10              List list = Arrays.asList(sa);
11              System.out.println("list:"+list);
12              System.out.println("list.size()="+list.size());
13      }
14   
15  }

6. Iterator and for-each

Before for-each came along, we wanted to iterate through each element in the ArrayList using the Iterator interface:

01  import java.util.Arrays;
02  import java.util.Iterator;
03  import java.util.List;
04   
05  public class Test {
06   
07      public static void main(String[] args) {
08   
09          // The Arrays class provides us with a convenient way to create list s
10          List<String> list = Arrays.asList("one", "two", "three", "four");
11   
12          // Convert to Iterator Instance
13          Iterator<String> it = list.iterator();
14   
15          //ergodic
16          while (it.hasNext()) {
17              System.out.println(it.next());
18          }
19   
20      }
21   
22  }

After the appearance of for-each, traversal became simpler:

01  import java.util.Arrays;
02  import java.util.Iterator;
03  import java.util.List;
04   
05  public class Test {
06   
07      public static void main(String[] args) {
08   
09          // The Arrays class provides us with a convenient way to create list s
10          List<String> list = Arrays.asList("one", "two", "three", "four");
11   
12          for (String s : list) {
13              System.out.println(s);
14          }
15   
16      }
17   
18  }

In this lecture: Map HashMap

In the previous lesson, we learned that Map is an interface. It is concerned with mapping relationships, where elements appear in pairs, keys and values are objects, and keys must be unique.It is very different from Collection in this respect.

1. Map interface

Common methods for Map interfaces are as follows:

put(K key, V value) Adds a specified key-value pair to the collection
putAll(Map

01  import java.util.Collection;
02  import java.util.HashMap;
03  import java.util.Map;
04  import java.util.Set;
05   
06  public class Test {
07   
08      public static void main(String[] args) {
09   
10          Map<Integer,String> map = new HashMap<Integer,String>();
11   
12          map.put(1, "Chinese cabbage");
13          map.put(2, "radish");
14          map.put(3, "eggplant");
15          map.put(4, null);
16          map.put(null, null);
17          map.put(null, null);
18   
19          System.out.println("map.size()="+map.size());
20          System.out.println("map.containsKey(1)="+map.containsKey(2));
21          System.out.println("map.containsKey(null)="+map.containsKey(null));
22          System.out.println("map.get(null)="+map.get(null));
23   
24          System.out.println("map.get(2)="+map.get(2));
25          map.put(null, "cucumber");
26          System.out.println("map.get(null)="+map.get(null));
27   
28          Set set = map.keySet();
29          System.out.println("set="+set);
30   
31          Collection<String> c = map.values();
32   
33          System.out.println("Collection="+c);
34   
35      }
36   
37  }

Compile and run the program to see the results:
1 map.size()=5
2 map.containsKey(1)=true
3 map.containsKey(null)=true
4 map.get(null)=null
5 map.get(2)=radish
6 map.get(null)=cucumber
7 set=[null, 1, 2, 3, 4]
8 Collection=[cucumber, cabbage, radish, eggplant, null]
2. Objects used as keys in HashMap must override the hashCode() and equals() methods of Objects

Let's take a look at an example I've spent an hour conceiving. Friends who are familiar with dragon guns will look kinder, set up dragon and dragon's nests, and then Map them together. We can see the number of treasures in their nests according to the dragon. The example is just to illustrate the knowledge of hashCode, so it doesn't have to be too storytelling and reasonable. Just take a look:

01  import java.util.HashMap;
02  import java.util.Map;
03   
04  public class Test {
05   
06      public static void main(String[] args) {
07   
08          // Dragon and its nest map
09          Map<dragon , Nest> map = new HashMap<dragon , Nest>();
10   
11          // Place four Dragons on the Continent of Klein in Map
12          map.put(new Dragon("Razor", 98), new Nest(98));
13          map.put(new Dragon("Bright mirror", 95), new Nest(95));
14          map.put(new Dragon("Blue", 176), new Nest(176));
15          map.put(new Dragon("Marley", 255), new Nest(255));
16   
17          // View the Treasure
18          System.out.println("How much treasure is there in the Blue Nest:" + map.get(new Dragon("Blue", 176)).getTreasure());
19      }
20   
21  }
22   
23  // Loong
24  class Dragon {
25   
26      Dragon(String name, int level) {
27          this.level = level;
28          this.name = name;
29      }
30   
31      // The name of the Dragon
32      private String name;
33   
34      // Dragon Level
35      private int level;
36   
37      public int getLevel() {
38          return level;
39      }
40   
41      public void setLevel(int level) {
42          this.level = level;
43      }
44   
45      public String getName() {
46          return name;
47      }
48   
49      public void setName(String name) {
50          this.name = name;
51      }
52   
53  }
54   
55  // Nest
56  class Nest {
57   
58      //The Dragon Constant I studied
59      final int DRAGON_M = 4162;
60   
61      // A treasure house
62      private int treasure;
63   
64      // Level of Dragon Residing
65      private int level;
66   
67      Nest(int level) {
68          this.level = level;
69          this.treasure = level * level * DRAGON_M;
70      }
71   
72      int getTreasure() {
73          return treasure;
74      }
75   
76      public int getLevel() {
77          return level;
78      }
79   
80      public void setLevel(int level) {
81          this.level = level;
82          this.treasure = level * level * DRAGON_M;
83      }
84   
85  }

Compile and run to see the results:

1 Exception in thread "main" java.lang.NullPointerException
2 at Test.main(Test.java:18)
We found an unexpected error, a null pointer error in line 18, which means that the get method did not get the expected nest object.

Here we'll look at why we can't get it.Let's first explain how HashMap works.

Suppose you now have a stub of six winning lottery tickets in five buckets (the first one is 1-5, the first one is 1, the second is 2, and so on). Now you have three lottery tickets to redeem, one is 113, one is 213, the other is 313.Now redeem the first one, take out the stub in bucket 1 and find that the stub number doesn't match yours, so your first one won't win.Continue to redeem the second sheet, there is no stub in bucket 2, so give up directly. Take out all the lottery stubs in bucket 3 and match them. Finally, you find that one stub happens to be 313. Congratulations on winning.

HashMap uses the same method to determine if one key object is the same as another. Each bucket is a hash code value for one key object, and the bucket holds the same lottery stub with the same hash code. If the hash codes are different, there must be no relevant elements. If the hash codes are the same, the key is also used.The equals() method of comparing if the same is considered the same key.Simply put, hashCode() is the same & equals ()==true.

Here we should understand that before we override the hashcode() and equals() methods of an object, they execute the corresponding methods in the Object.The hashcode () of an Object is calculated from where the object is stored in memory, and each instance of the object is different.The simpler implementation of an Object's equals() is to see if two objects are==, that is, they are not the same unless they are the same object.So while the examples above are all Dragons by the name of Bire, they are not recognized as identical in HashMap.

So we only have to override the hashCode() and equals() methods of the Key object to avoid this, but Eclipse can help us automatically generate a class of hashCode() and equals(), so let's try these two methods again:

001 import java.util.HashMap;
002 import java.util.Map;
003  
004 public class Test {
005  
006     public static void main(String[] args) {
007  
008         // Dragon and its nest map
009         Map<dragon , Nest> map = new HashMap<dragon , Nest>();
010  
011         // Place four Dragons on the Continent of Klein in Map
012         map.put(new Dragon("Razor", 98), new Nest(98));
013         map.put(new Dragon("Bright mirror", 95), new Nest(95));
014         map.put(new Dragon("Blue", 176), new Nest(176));
015         map.put(new Dragon("Marley", 255), new Nest(255));
016  
017         // View the Treasure
018         System.out.println("How much treasure is there in the Blue Nest:" + map.get(new Dragon("Blue", 176)).getTreasure());
019     }
020  
021 }
022  
023 // Loong
024 class Dragon {
025  
026     Dragon(String name, int level) {
027         this.level = level;
028         this.name = name;
029     }
030  
031     // The name of the Dragon
032     private String name;
033  
034     // Dragon Level
035     private int level;
036  
037     public int getLevel() {
038         return level;
039     }
040  
041     public void setLevel(int level) {
042         this.level = level;
043     }
044  
045     public String getName() {
046         return name;
047     }
048  
049     public void setName(String name) {
050         this.name = name;
051     }
052  
053     @Override
054     public int hashCode() {
055         final int PRIME = 31;
056         int result = 1;
057         result = PRIME * result + level;
058         result = PRIME * result + ((name == null) ? 0 : name.hashCode());
059         return result;
060     }
061  
062     @Override
063     public boolean equals(Object obj) {
064         if (this == obj)
065             return true;
066         if (obj == null)
067             return false;
068         if (getClass() != obj.getClass())
069             return false;
070         final Dragon other = (Dragon) obj;
071         if (level != other.level)
072             return false;
073         if (name == null) {
074             if (other.name != null)
075                 return false;
076         } else if (!name.equals(other.name))
077             return false;
078         return true;
079     }
080  
081 }
082  
083 // Nest
084 class Nest {
085  
086     //The Dragon Constant I studied
087     final int DRAGON_M = 4162;
088  
089     // A treasure house
090     private int treasure;
091  
092     // Level of Dragon Residing
093     private int level;
094  
095     Nest(int level) {
096         this.level = level;
097         this.treasure = level * level * DRAGON_M;
098     }
099  
100     int getTreasure() {
101         return treasure;
102     }
103  
104     public int getLevel() {
105         return level;
106     }
107  
108     public void setLevel(int level) {
109         this.level = level;
110         this.treasure = level * level * DRAGON_M;
111     }
112  
113 }

Compile and run to see the results:
1 How much treasure is there in the Birley Nest: 128922112
It's not easy to ^^ output normally this time
Well, that's it.

Posted by AbsolutelyFreeW on Sun, 30 Jun 2019 11:05:01 -0700