Use of set in Java __java

Source: Internet
Author: User
Tags delete key int size set set

Using set in Java makes it easy to save the type you want in a variable as a collection type. The main application is in the display list. Set is a collection that does not contain duplicate elements. Rather, the set does not contain elements that satisfy e1.equals (E2) for E1 and E2, and contains a maximum of one null element. As the name implies, this interface mimics the mathematical set abstraction.

Here's an example of using set in Java and hopefully it will help.

Import java.util.*;
public class Test {

/**
* @param args
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
Set set=new hashset ();
Set.add ("abc");
Set.add ("CDE");
Set.add ("EFG");
Set.add ("FGH");
Set.add ("abc"); Repeated abc,set will be automatically removed
System.out.println ("size=" + set.size ());
List List = new ArrayList ();
List.add ("abc");
List.add ("AAA");
List.add ("fff");
Set.addall (list); Add the values in the list to the set and remove the duplicate ABC
System.out.println ("size=" + set.size ());
for (Iterator it = Set.iterator (); It.hasnext (); )
{
System.out.println ("value=" +it.next (). toString ());
}
}

}

***************************************************************

The idea of a collection of Java is to think about arrays
Arrays are fixed in size, and the same array can only hold data of the same type (base type/reference type)
A Java collection can store and manipulate a set of data that is not fixed in number.
All Java collections are located in the Java.util package.
A Java collection can only hold data of reference types and cannot hold basic data types.
There are three main types of Java collections:
Set (SET)
List (listing)
Map (map)
Collection interface
Collection is the most basic collection interface, declaring a common method for Java collections, which include only set and list.
Both Set and list inherit conllection,map.
Methods for collection interfaces:
Boolean Add (Object O): Adding a reference to an object in the collection
void Clear (): Deletes all objects in the collection, that is, they no longer hold references to these objects
Boolean IsEmpty (): Determines whether the collection is empty
Boolean contains (object O): Determining whether a reference to a particular object is held in the collection
Iterartor iterator (): Returns a Iterator object that can be used to traverse the elements in the collection
Boolean remove (Object O): Deletes a reference to an object from the collection
int size (): Returns the number of elements in the collection
Object[] ToArray (): Returns an array that contains all the elements in the collection
About: the iterator () and ToArray () methods are all elements of a collection that return a iterator object, which returns an array that contains all the elements in the collection.
the iterator interface declares the following methods:
Hasnext (): Determines whether the elements in the collection are traversed and, if not, returns true
Next (): Returns the next element
Remove (): Deletes the previous element returned by the next () method from the collection.
Set (SET):
Set is the simplest kind of collection. Objects in the collection are not sorted in a particular way, and there are no duplicate objects.
The set interface mainly implements two implementation classes:
The Hashset:hashset class accesses objects in the collection according to the hashing algorithm, and the access speed is faster
The Treeset:treeset class implements the SortedSet interface, which is able to sort the objects in the collection.
Use of Set:
There is a reference to the object, no duplicate objects
Set set=new hashset ();
String S1=new string ("Hello");
String s2=s1;
String S3=new string ("World");
Set.add (S1);
Set.add (S2);
Set.add (S3);
System.out.println (Set.size ());//The number of objects in the Print collection is 2.
The set's Add () method determines whether the object is already stored in the collection.
Boolean isexists=false;
Iterator Iterator=set.iterator ();
while (It.hasnext ()) {
String Oldstr=it.next ();
if (Newstr.equals (OLDSTR)) {
Isexists=true;
}
}

list (listing):
The feature of a list is that its elements are stored in a linear fashion, and the collection can hold duplicate objects.
The main implementation classes of the list interface include:
ArrayList (): Represents the length can change the group. The element can be randomly accessed and inserted into the ArrayList ()
Slow to delete elements.
LinkedList (): In the implementation of the use of linked list data structure. Fast insertion and deletion, slow access.
For random access to a list, it's just random to retrieve elements at a particular location.
The Get (int index) method of the List is put back to the object in the collection at the index specified by the parameter index, and the subscript starts with "0".
The two most basic ways to retrieve all of the objects in a collection:
1: With the For Loop and get () method:
for (int i=0; i<list.size (); i++) {
System.out.println (List.get (i));
}
2: Using Iterators (iterator):
Iterator It=list.iterator ();
while (It.hashnext) {
System.out.println (It.next);
}
Map (map):
A map is a collection of key and value object mappings, each of which contains a pair of key objects and value objects.
Map does not inherit from collection interface
When an element is retrieved from the Map collection, the corresponding value object is returned whenever the key object is given.
Common methods of Map:
1 Add, delete operation:
Object put (object key, Object value): Adding elements to the collection
Object remove (Object key): Delete key-related elements
void Putall (Map t): Adds all elements from a particular image to the image
void Clear (): Removes all mappings from the image
2 Query operation:
Object get (Object key): Gets the value associated with the keyword key
The key object in the Map collection does not allow duplication, which means that any two key objects are compared by the Equals () method to False.
However, you can map any number of keys to the same value object alone.
Conllections: Collection Utility class
Conllections provides a practical static method for Java collections
Summary:
Java collection of basic usage, are summed up, these are the most commonly used Java set, the specific other, but also refer to the JDK Help document, hehe on the application of MAP, there are many, specifically this, Conllections provides a lot of list/map practical methods, Very useful for normal development.

Boolean ContainsKey (Object key): Determining whether a keyword key exists in the image
Boolean Containsvalue (Object value): Determining whether a value is present in the image
int size (): Returns the number of mappings in the current image
Boolean IsEmpty (): Determine if there are any mappings in the image
This article from Csdn Blog, reproduced please indicate the source: http://blog.csdn.net/wordinput/archive/2010/01/22/5223876.aspx
List saves objects in the order in which they are entered, without sorting or editing operations. Set accepts only once for each object and uses its own internal sorting method (usually, you only care about whether an element belongs to the set, not the order of it--otherwise you should use the list). Map also saves one copy of each element, but this is based on the "key", and the map has a built-in sort, and therefore does not care about the order in which the elements are added. If the order in which you add elements is important to you, you should use Linkedhashset or Linkedhashmap.
the function method of list
There are actually two kinds of lists: One is the basic ArrayList, the advantage is the random access element, the other is the more powerful linkedlist, it is not designed for fast random access, but has a more general approach.
List: Order is the most important feature of the list: it guarantees that the order of the elements is maintained. List adds a number of methods to collection that allow you to insert and remove elements into the middle of the list (this is recommended only for linkedlist use.) A list can generate Listiterator, using it to traverse the list in two directions, or to insert and remove elements from the middle of the list.
ArrayList: A list implemented by an array. Allows quick random access to elements, but inserts and removes elements in the middle of the list is slow. Instead of inserting and removing elements, listiterator should only be used to traverse the ArrayList from the back forward. Because it's a lot bigger than the linkedlist overhead.
LinkedList: The sequential access is optimized, and the overhead of inserting and deleting into the list is not significant. Random access is relatively slow. (use ArrayList instead.) Also has the following methods: AddFirst (), AddLast (), GetFirst (), GetLast (), Removefirst (), and Removelast (), these methods (not defined in any interface or base class) Enables LinkedList to be used as stacks, queues, and bidirectional queues.
the function method of set
The set has exactly the same interface as collection, so there is no additional functionality, unlike the two different lists that preceded it. In fact set is collection, but behavior is different. (This is a typical application of inheritance and polymorphic thinking: behavior that behaves differently.) Set does not save duplicate elements (more responsible for determining the same element)
Set: Each element that is stored in the set must be unique because the set does not save the repeating element. Elements that join a set must define the Equals () method to ensure the uniqueness of the object. Set has exactly the same interface as collection. The set interface does not guarantee the order of elements to be maintained.
HashSet: Set for quick find design. The object that is stored in the HashSet must define HASHCODE ().
TreeSet: Save order set, bottom is tree structure. Use it to extract ordered sequences from set.
Linkedhashset: Has a hashset query speed and internally uses a linked list to maintain the order of elements (in the order of insertion). So when you use iterators to traverse set, the results are displayed in the order in which the elements are inserted.
the functional method of map
Method put (Object key, object value) adds a "value" (What you Want) and a key that is associated with the value (used to find it). The method get (Object key) returns the value associated with the given key. You can use ContainsKey () and Containsvalue () to test whether a "key" or "value" is included in the map. The standard Java class library contains several different map:hashmap, TreeMap, Linkedhashmap, Weakhashmap, and Identityhashmap. They all have the same basic interface map, but behavior, efficiency, sorting strategies, the lifecycle of saving objects, and the policy of determining "key" equivalence are different.
Execution efficiency is a big problem in map. Look at what gets () to do, and you'll see why it's rather slow to search for "keys" in ArrayList. And that's where hashmap is raising speed. HashMap uses a special value, called hash code, to replace a slow search for keys. "Hash code" is "relatively unique" to represent an int value of an object, which is generated by converting some of the object's information. All Java objects can produce hash codes, because Hashcode () is a method defined in the base class object.
HashMap is a quick query using an object's Hashcode (). This method can significantly improve performance.
MAP: Maintains the association of key-value pairs so that you can find the value by "key"
Hashmap:map is based on a hash table implementation. The cost of inserting and querying key-value pairs is fixed. The capacity capacity and load factor load factor can be set through the constructor to adjust the performance of the container.
Linkedhashmap: Similar to HashMap, but when iterating through it, the order in which "key value pairs" is obtained is its insertion order, or the order in which the least recent (LRU) is used. Just a little slower than HashMap. It is faster when iterating through the access, because it uses a linked list to maintain the internal order.
TREEMAP: The implementation of the data structure based on the red-black tree. When you view key or key-value pairs, they are sorted (in order by Comparabel or comparator). TreeMap is characterized by the fact that the results you get are sorted. TreeMap is the only map with a Submap () method that can return a subtree.
Weakhashmao: The object used in the weak key (weak key) Map,map is also allowed to be released: This is designed to solve special problems. This key can be reclaimed by the garbage collector if a reference other than the map points to a key.
Identifyhashmap: Hash map that uses = = instead of equals () to compare "keys". Designed to solve specific problems.

Related Article

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.