What about set unordered?

Source: Internet
Author: User

In Java, there are many different structures for organizing objects, and set (set) is one of them, which is itself an interface, and the order of its iterations depends on its specific implementation.

Typical implementations include the following:

HashSet: A hash table stores information by using a mechanism called hashing, and the elements are not stored in a particular order;
Linkedhashset: maintains a linked table of the collection in the order in which the elements are inserted, allowing iterations in the collection in the order in which they are inserted;
TreeSet: Provides an implementation that uses a tree structure to store a set interface, where objects are stored in ascending order, and the time to access and traverse is fast.

Set has a variety of, hashset,treeset and linkedhashset more common, hashset most commonly used. Linkedhashset are orderly and hashset are disordered. Linkedhashset is to store data in the form of a chain list, and hashset to store data with hash hashes. List also divided into several kinds, mainly ArrayList and LinkedList, are ordered, wherein the ArrayList analogy array, LinkedList analogy linked list. ArrayList is a thread that is not synchronized, that is, multiple threads simultaneously manipulate a list so the consistency of the data stored in the list is not guaranteed. Vectors are thread-synchronized, which means thread-safe. Search
This answer was adopted by the questioner

The set collection is not guaranteed in the order of the elements in the collection.

The list collection will have a sequential list whose elements are stored in a linear fashion

Set it does not allow repeating elements and allows for elements with null values, but can have only one null element

Both Set and list inherit the Conllection

 sequentially outputting elements in the set collection in Java

Traversal of Set    //1. Iterative traversal:  set<string> set = new Hashset<string> ();  Iterator<string> it = Set.iterator ();  while (It.hasnext ()) {    String str = It.next ();    System.out.println (str);  }    2.for Loop traversal: For  (String str:set) {        System.out.println (str);  }      The advantages are also reflected in generics if the set is stored in Object    set<object> set = new Hashset<object> ();  For loop traversal: for  (Object obj:set) {        if (obj instanceof integer) {                  int aa= (integer) obj;               } else if (obj instanceof string) {                 string aa = (string) obj               }                ...  }   

  

The set set in Java is a collection that does not contain duplicate elements, let's first look at the traversal method

package Com.sort;  Import Java.util.HashSet;  Import Java.util.Iterator;    Import Java.util.Set; /** * A collection that does not contain duplicate elements. More specifically, the set does not contain elements that satisfy e1.equals (E2) to E1 and E2, * @author Owner * */public class SetTest2 {public static void Mai                    N (string[] args) {set<string> Set = new hashset<string> ();          Set.add ("a");          Set.add ("B");          Set.add ("C");          Set.add ("D");                    Set.add ("E"); Set.add ("E");//cannot be put into duplicate data/** * Traversal method one, iterating through */for (iterator<string> Itera          Tor = Set.iterator (); Iterator.hasnext ();) {System.out.print (Iterator.next () + "");          } System.out.println ();                    System.out.println ("********************");          /** * for Enhanced loop traversal */for (String value:set) {System.out.print (value+ ""); }      }  }

  


Note: Here the set set is put in a string type, if we put in a class instance of our own definition, such as the person class instance, this time we have to re-hashcode and equal methods, with their own key fields to rewrite, Because when using HashSet, the Hashcode () method is called to determine if the hash code value of the object already stored in the collection is the same as the hash code value of the added object, and if it is inconsistent, add it directly, and if it is consistent, then compare the Equals method, If the Equals method returns true to indicate that the object has been added, no new objects will be added or added.

The following is an analysis of another important implementation class TreeSet of the set set,

The TreeSet uses the natural order of the elements to sort the elements, or to sort based on what is provided when the set is created Comparator , depending on the construction method used.

In layman's terms, they can be displayed in sorted lists or sorted by specified rules.

set<string> set = new Treeset<string> ();                    Set.add ("F");          Set.add ("a");          Set.add ("B");          Set.add ("C");          Set.add ("D");          Set.add ("E");                    SYSTEM.OUT.PRINTLN (set);  

  


output: [A, B, C, D, E, F]

Output by sort

So what if we want him to reverse the output? Of course there are many ways. Here I'm using a rule to get him to reverse the output.

 PackageCom.sort; ImportJava.util.Comparator; ImportJava.util.Iterator; ImportJava.util.Set; ImportJava.util.TreeSet;  Public classTreeSetTest3 { Public Static voidMain (string[] args) {Set<String> set =NewTreeset<string> (Newmycomparator ()); Set.add (A); Set.add ("B"); Set.add (C); Set.add ("D"); Set.add (E); Set.add (A);  for(Iterator<string> Iterator =set.iterator (); Iterator.hasnext ();) {System.out.print (Iterator.next ()+" "); }      }  }    classMycomparatorImplementsComparator<string>{@Override Public intCompare (String O1, String O2) {returnO2.compareto (O1);//Descending arrangement    }        }  


output: E D C b a a

What if we put a class type that we define ourselves in the set set?

Note: Be sure to define a collation class to implement the comparator interface, similar to the method above

Package com.sort;  Import Java.util.Comparator;  Import Java.util.Iterator;  Import Java.util.Set;    Import Java.util.TreeSet; public class TreeSetTest2 {public static void main (string[] args) {set<person> Set = new TREESET&L T                    Person> (New Personcomparator ());          person P1 = new person (10);          person P2 = new person (20);          Person P3 = new person (30);                    person P4 = new person (40);          Set.add (p1);          Set.add (p2);          Set.add (p3);                    Set.add (p4); for (iterator<person> Iterator = Set.iterator (); Iterator.hasnext ();) {System.out.print (Iterator.next (). s          Core+ "");            }}} class person{int score;      Public person (int score) {This.score = score;      } public String toString () {return string.valueof (This.score); }} class Personcomparator implements comparator<person>{@Override      public int Compare (person O1, person O2) {return o1.score-o2.score; }        }

  


Output: 10 20 30 40

If you follow the reverse order of a person's score, you only need to change the O2.score-o1.score in the Compare method


What about set unordered?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.