Basic knowledge of Java (iii)

Source: Internet
Author: User
Tags comparable int size set set

Collection

The JDK class library provides a Java collection in which all Java collection classes are located in the Java.util package. Unlike Java arrays, basic type data cannot be stored in a Java collection, and only references to objects are stored. For the convenience of expression, the following refers to "the objects in the collection" as "Objects in the collection".

There are three main types of collections in Java:

1. Set: Unordered, and no duplicate objects.

2. List: Ordered (put in order), repeatable.

3. Map: Each element in the collection contains a pair of key objects and value objects, and there are no duplicate key objects in the collection, and value objects can be duplicated.

First, collection and iterator interface

A common method for set and list is declared in the collection interface:

Boolean Add (Object O): Adds a reference to an object to the collection;

void Clear (): Deletes all object references in the collection, that is, no longer holding references to those objects;

Boolean contains (object O): Determines whether a reference to a particular object is held in the collection;

Boolean IsEmpty (): Determines whether the collection is empty;

Iterator 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[] Toattray (): Returns an array that contains all the elements in the collection;

The iterator interface hides the data structure of the underlying collection, providing the client with a uniform way to traverse the various types of collections. To declare a method in the iterator interface:

Hasnext (): Determines whether the elements in the collection are traversed, if not, return true;

Next (): Returns the next element;

Remove (): Deletes the previous element returned by the next () method from the collection;

Two, Set
The simplest kind of collection in which objects in the collection are unordered and cannot be duplicated. The main implementation classes include:

1. HashSet: According to the hashing algorithm to access the objects in the collection, access speed is relatively fast;

2. Linkedhashset:hashset subclass, not only realizes the hash algorithm, but also realizes the chain table data structure, the link table data structure can improve inserts and deletes the element the performance;

3. TreeSet: Implements SortedSet interface, has the sorting function;

General usage: The Set collection holds references to objects, and there are no duplicate objects.
When a new object is added to the set set, the set's Add method determines whether the object already exists in the collection. It traverses the existing object and compares the new object and the existing object with equality by the Equals method.

Boolean isexist = false;
Iterator it = Set.iterator ();
while (It.hasnext ()) {
       String oldstr = It.next ();
       if (Newstr.equals (OLDSTR)) {
            isexists = true;
            break;
        }
}
Example:

Set set = new HashSet ();
string S1 = new String ("Hello");
String s2 = new string ("Hello");
Set.add (S1);
Set.add (S2);
System.out.println (Set.size ()); The number of objects in the collection is 1;
1 HashSet

According to the hashing algorithm to access the objects in the collection, the access speed is relatively fast. When an object is added to the collection, HashSet calls the object Hashcode () method to obtain the hash code, and then further calculates the location of the object in the collection based on the hash code. The Hashcode () method and the Equals () method are defined in the object class, and the Equals () method of the object class compares the objects for equality by memory address, so if Object.Equals (Object2) is true, Indicates that the OBJECT1 variable and the object2 variable actually refer to the same object, then the hash code for OBJECT1 and Object2 is definitely the same. To ensure that the HashSet works correctly, the hash code is equal when the two-year object compares the result with the Equals () method to True. If the user-defined customer class overrides the Equals () method of the object class, but does not overwrite the Hashcode () method of the object class, it causes the Customer1.equals (Customer2) to be true. The hash code for CUSTOMER1 and Customer2 is not necessarily the same, which makes the hashset not work properly.

public class Customer {
      private String name;
      private int age;

      Public Customer (String name, int age) {
             this.name = name;
             This.age = age;
      }
                         
      Public String GetName () {return
             name;
      }

      public int getage () {return age
             ;
      }

      public boolean equals (Object o) {
            if (this==o) is return true;                          
            if (!) ( o instanceof Customer) return false;
            Customer other = (customer) o;

            if (This.name.equals (Other.getname ()) && this.age.equals (Other.getage ()) {return
                   true;
             else return 
                   false;
            }
 
The following program adds two customer objects to the HashSet.
Set set = new HashSet ();
Customer customer1 = new Customer ("Tom");
Customer Customer2 = new Customer ("Tom");
Set.add (customer1);
Set.add (customer2);
System.out.println (Set.size ());         Print out 2
The reason for this is that the hash code for CUSTOMER1 and Customer2 is different, so the two are calculated differently for the customer object, so they are placed in different places in the focus. The following hashcode () method should be added:
public int hashcode () {
       int. result;
       result = (Name==null?0:name.hashcode ());
       result = 29*result + age;
       return result;
}
2) TreeSet

The TreeSet implements the SortedSet interface, which is able to sort the objects in the collection. When TreeSet adds an object to the collection, it is inserted into an ordered sequence of objects. So how does the TreeSet sort the objects? TreeSet supports two sorting methods: natural sorting and custom sorting. By default, TreeSet uses the natural sort method:

A. Natural sequencing

In the JDK class library, a subset of the classes implement comparable interfaces, such as integers, double, and string. The comparable interface has a CompareTo (Object O) method that returns an integer type. For X.comapreto (y), such as

Returns 0, indicating equal x and Y

The return value is greater than 0, indicating X>y

The return value is less than 0, indicating X<y

TreeSet calls the object's CompareTo () method to compare the size of objects in the collection, and then to sort in ascending order, which is called a natural sort.

Some classes in the JDK class library that implement the comparable interface are sorted as follows:

Byte, short, Integer, Long, Double, Float: sorted by number size;

Character: Sort by the number size of the Unicode value of the character;

String: Sorts by Unicode values of characters in a string;

With natural sorting, only the same types of objects can be added to the TreeSet, and the objects must implement the comparable interface. Otherwise, a ClassCastException exception is thrown. When you modify the properties of an object, TreeSet is not reordered. The most appropriate sort of treeset is immutable classes (their object's properties cannot be modified).

B. Customized ordering

In addition to natural sorting, TreeSet also supports customized sorting. The Java.util.Comparator interface provides a specific sort method, which has a compare (object X, Object Y) method for comparing the size of two objects, when compare (X,y):

Returns 0, indicating equal x and Y

The return value is greater than 0, indicating X>y

The return value is less than 0, indicating X<y

If you want TreeSet to be sorted in descending order by the Name property of the Customer object, you can first create an implementation comparator interface class Customercomparator, see:

Import java.util.*; public class Customercomparator implements Comparator {public int compare (object O1, Object O2) {Cust
             Omer C1 = (Customer) O1;
             Customer C2 = (customer) O2;
             if (C1.getname (). CompareTo (C2.getname ()) >0) return-1;
if (C1.getname (). CompareTo (C2.getname ()) <0) return 1;
      <span style= "White-space:pre" > </span> return 0;
             public static void Main (string[] args) {Set set = new TreeSet (new Customercomparator ());
             Customer customer1 = new Customer ("Tom", 15);
             Customer Customer3 = new Customer ("Jack", 16);
             Customer Customer2 = new Customer ("Mike", 26);
             Set.add (Customer1);
             Set.add (CUSTOMER2);
             Set.add (CUSTOMER3);
                      
             Iterator it = Set.iterator ();
                     while (It.hasnext ()) {Customer customer = It.next (); SYSTEM.OUT.PRINTLN (CustOmer.getname () + "" + customer.getage ());
 }
      }
}

Print output:
Tom Mike Jack 16

Third, List
The main feature is that its elements are stored in a linear fashion, allowing duplicate objects to be stored in the collection. The main implementation classes include:

1. ArrayList: Represents a variable length array. Allows fast random access to elements, but it is slower to insert and delete elements into the ArrayList;

2. LinkedList: In the implementation of the use of linked list structure. Sequential access is optimized to insert and delete elements into the list faster and with relatively slower random access. Random access is the retrieval of elements at a specific index location.

Traversal mode:

A.list.get (i);//retrieving Objects by index

B.iteratoor it = List.iterator ();

It.next ();

Iv. Map
Map is a collection that maps key and value objects, and each element contains a pair of key objects and value objects. When you add an element to a map collection, you must provide a pair of key objects and value objects, and when you retrieve an element from the map collection, the corresponding value object is returned whenever the key object is given.

Map.put ("2", "Tuesday");
Map.put ("3", "Wednsday");
Map.put ("4", "Thursday");
String day = Map.get ("2");    Day's value is "Tuesday"
The key object in the Map collection does not allow duplicates, such as adding multiple value objects with the same key object, and the first time the value object that is added is overwritten. For value objects, there is no uniqueness requirement to map any number of key objects to the same value object.
Map.put ("1", "Mon");
Map.put ("1", "Monday");      "1" At this time corresponds to "Monday"
map.put ("One", "Monday");    "One" corresponds to "Monday" at this time
The map has two more common implementations:

1) HashMap

According to the hash algorithm to access the key object, there is good access performance, in order to ensure that HashMap can work properly, and hashset, when two key objects through the Equals () method comparison is true, the two key objects Hashcode () method return the same hash code.

2) TreeMap

The SortedMap interface is implemented, and the key objects can be sorted. Like TreeSet, TreeMap also supports both natural ordering and custom sorting.

Map map = new TreeMap ();
Map.put ("1", "Monday");
Map.put ("3", "Wednsday");
Map.put ("4", "Thursday");
Map.put ("2", "Tuesday");

Set keys = Map.keyset ();
Iterator it = Keys.iterator ();
while (It.hasnext ()) {
      string key = (String) it.next ();
      String value= (String) map.get (key);
      SYSTEM.OUT.PRINTLN (key + "" + value);
}

Print output:

1 Monday

2 Tuesday

3 Wednsday

4 Thursday

Describes four ways to traverse a map:

The first method (common one, as in the previous example):
For (String Key:map.keySet ()) {
System.out.println ("key=" + key + "and value=" + map.get (key));
}
The second method:
Iterator<map.entry<string, string>> it = Map.entryset (). iterator ();
while (It.hasnext ()) {
map.entry<string, string> Entry = It.next ();
System.out.println ("key=" + entry.getkey () + "and value=" + entry.getvalue ());
}
The third method (232 methods have the same principle):
For (map.entry<string, string> entry:map.entrySet ()) {
System.out.println ("key=" + entry.getkey () + "and value=" + entry.getvalue ());
}

Fourth method (not commonly used):

For (String v:map.values ()) {
System.out.println ("value=" + V);
}

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.