Java basics 16-collection framework

Source: Internet
Author: User
Tags comparable

16-1, set frame Vector set

1. Vector is a Vector. The bottom layer is an array structure. You can use its elements () method to obtain an Enumeration object. This object has the same functions as Iterator, iterator has more removal operations than him, so now it is generally not necessary to use Vector, Iterator.

Example of elements that iterate over a Vector set through Enumeration:

public class VectorDemo {public static void main(String[] args) {Vector v = new Vector();v.addElement("abc1");v.addElement("abc2");v.addElement("abc3");v.addElement("abc4");Enumeration en = v.elements();while(en.hasMoreElements()) {System.out.println("nextElements:" + en.nextElement());}Iterator it = v.iterator();while(it.hasNext()) {System.out.println("next:" + it.next());}}}

Replacing Enumeration with Iterator is because the name of Enumeration and the method in it is too long to simplify writing.

16-2, sorted list set

1. Basic operations

AddFirst (): adds an element to the header.

GetFirst (): gets the first element but does not delete it.

RemoveFirst (): gets the first element and deletes it.

2. Example:

Public class Demo {public static void main (String [] args) {shortlist link = new shortlist (); link. addFirst ("abc1"); link. addFirst ("abc2"); link. addFirst ("abc3"); link. addFirst ("abc4"); System. out. println (link); System. out. println (link. getFirst (); // abc4System. out. println (link. getFirst (); // abc4, do not delete // System. out. println (link. removeFirst (); // abc4 // System. out. println (link. removeFirst (); // abc3while (! Link. isEmpty () {System. out. println (link. removeLast (); // abc1, abc2, abc3, abc4 }}}

16-3, Skip List exercise-simulate stack and queue

Requirement: Use the queue list to simulate a stack or queue data structure.

STACK: Advanced and later.

Queue: FIFO.

We should describe a container that provides users with a container object to complete one of the two structures.

Public class synchronized test {public static void main (String [] args) {DuiLie d1 = new DuiLie (); d1.myAdd ("abc1"); d1.myAdd ("abc2 "); d1.myAdd ("abc3"); d1.myAdd ("abc4"); while (! D1.isNull () {System. out. println (d1.myGet () ;}} class Duilie {private writable list; public DuiLie () {list = new writable list ();} // The public void myAdd (Object obj) {list. addLast (obj);} public Object myGet () {return list. removeFirst ();} public boolean isNull () {return list. isEmpty ();}}

The queue is implemented.

16-4, ArrayList stores custom objects

For example, store the Person object.

Person class:

public class Person {private String name;private int age;public Person() {super();}public Person(String name, int age) {super();this.name = name;this.age = age;}public String getName() {return this.name;}public void setName(String name) {this.name = name;}public int getAge() {return this.age;}public void setAge(int age) {this.age = age;}}

ArrayList stores the User-Defined Object Person class.

Public class ArrayListTest {public static void main (String [] args) {ArrayList al = new ArrayList (); al. add (new Person ("lisi1", 21); al. add (new Person ("lisi2", 22); al. add (new Person ("lisi3", 23); al. add (new Person ("lisi4", 24); Iterator it = al. iterator (); while (it. hasNext () {// System. out. println (Person) it. next ()). getName () + ":" + (Person) it. next ()). getAge ();/* the above method will produce an error. In SOP, every next time, you want to take an object, that is The first next reads the name of lisi1 and jumps to the next object. The next object reads the age of lisi2, so the result of lisi1, 22, lisi3, 24 appears; in the following method, create an object and assign the read object to p, so that no SOP error occurs. */Person p = (Person) it. next (); System. out. println (p. getName () + "---" + p. getAge ());}}}

16-5, HashSet set

1. Set: the elements cannot be repeated. The order of the retrieved elements is not necessarily the same as that of the stored elements. Unordered because the addresses of elements in the HashSet are calculated using the hash algorithm of the system, and the locations calculated by the hash algorithm are unordered.

The methods in the Set interface are the same as those in the Collection interface.

The internal data structure of a HashSet is a hash table, which is not synchronized and the elements in the set are unique.

Example:

Public class HashSetDemo {public static void main (String [] args) {HashSet hs = new HashSet (); hs. add ("hehe"); hs. add ("heihei"); hs. add ("haha"); hs. add ("xixi"); // hs. add ("hehe"); // if there are two hehe, only one is printed at the end, because repeated Iterator it = hs is not allowed. iterator (); while (it. hasNext () {System. out. println (it. next ());}}}

The output results of this program are unordered.

16-6, hash table

1. A hash table is a hash algorithm used by the kernel to store data. It can be quickly searched, and its underlying structure is an array, the hash algorithm can calculate the corresponding position in the array based on the data attributes and store the data directly. No traversal is required when the data is obtained. The hashCode method is called to calculate the position, if there is no such element at the corresponding position, you do not need to check whether the elements at other locations match.

2. perform the following steps to determine whether the elements are the same in the hash table:

(1) Determine whether the hash values of the two elements are the same. If they are the same, determine whether the content of the two objects is the same.

(2) When the hash value is the same, the hashCode method of the object is used to determine that the content is the same and the equals method is used.

Note: If the hash value is different, you do not need to determine equals.

16-7. HashSet stores custom objects

1. How can we ensure the uniqueness of HashSet elements?

The hashCode method and equals method of the object are used to determine the uniqueness of the object.

If the hashCode value of an object is different, the object is directly stored in the hash table without the need to judge the equals method.

If the hashCode value of the object is the same, it is necessary to judge whether the equals method of the object is true again. If it is true, it is treated as the same element and stored.

Remember: if an element is to be stored in a HashSet set, it must overwrite the hashCode and equals methods.

In general, if a defined class produces many objects, such as people, students, and books, it is usually necessary to overwrite the equals and hashCode methods.

This is the basis for determining whether objects are the same.

2. Store custom object instances:

Public class Person {private String name; private int age; public Person () {super ();} public Person (String name, int age) {super (); this. name = name; this. age = age;} public String getName () {return this. name;} public void setName (String name) {this. name = name;} public int getAge () {return this. age;} public void setAge (int age) {this. age = age;} // override the hashCode and equals Methods @ Overridepublic int hashCode () {return na Me. hashCode () + age * 27 ;}@ Overridepublic boolean equals (Object obj) {if (this = obj) {return true ;} if (! (Obj instanceof Person) {throw new ClassCastException ("type error");} Person p = (Person) obj; return this. name. equals (p. name) & this. age = p. age ;}}

Storage custom object class:

// Store the Person object in the HashSet set. If the name and age are the same, the object is treated as the same Person with the same element. Public class HashSetTest {public static void main (String [] args) {HashSet hs = new HashSet ();/* the combination of HashSet and data structure is a hash table, so when storing elements, use the hashCode method of the element to determine the location. If the location is the same, use the equals method of the element to determine whether the location is the same. */Hs. add (new Person ("lisi4", 24); hs. add (new Person ("lisi7", 27); hs. add (new Person ("lisi1", 21); hs. add (new Person ("lisi9", 29); hs. add (new Person ("lisi7", 27); // If the hashCode and equals methods are not overwritten, lisi7, 27 will be output here, and the uniqueness of Iterator it = hs is not guaranteed. iterator (); while (it. hasNext () {Person p = (Person) it. next (); System. out. println (p. getName () + "... "+ p. getAge ());}}}

16-8, set frame-Exercises

Requirement: retrieve the repeated elements in the ArrayList.

Public class ArrayListTest {public static void main (String [] args) {ArrayList al = new ArrayList (); al. add ("abc1"); al. add ("abc2"); al. add ("abc2"); al. add ("abc1"); al. add ("abc"); System. out. println (al); al = getSingleElement (al); System. out. println (al);} public static ArrayList getSingleElement (ArrayList al) {// defines a temporary container ArrayList temp = new ArrayList (); // iterates the al set Iterator it = al. iterator (); while (it. hasNext ()){ Object obj = it. next (); // determines whether the elements to be iterated exist in the Temporary container. If (! Temp. contains (obj) {temp. add (obj) ;}} return temp ;}}

Result: abc1, abc2, abc2, abc1, and abc

Abc1, abc2, abc

16-9, LinkedHashSet set

Features: Implements hash tables and link lists with Set interfaces that can be iterated.

To put it bluntly, this set ensures that the object is unique and ordered. HashSet is unordered.

For example:

public class LinkedHashSetDemo {public static void main(String[] args) {HashSet hs = new LinkedHashSet();hs.add("haha");hs.add("hehe");hs.add("heihei");hs.add("xixi");Iterator it = hs.iterator();while(it.hasNext()) {System.out.println(it.next());}}}

Result: haha hehe heihei xixi

The input and output orders are the same.

16-10, TreeSet set

1. This Set can sort the elements in the Set in the specified order (in the natural order ).

For example:

TreeSet ts = new TreeSet (); ts. add ("zhangsan", 22); ts. add ("lisi", 23); ts. add ("wangwu", 27); Iteration...

The second ts. add error is found.

Originally, to sort a TreeSet, you must have the sorting function. For Person, how can the sorting function be implemented?

You should use the Comparable interface in java. lang. To enable the sorting function for the Person, you can implement the Comparable interface.

Description of the Comparable interface:

This interface forcibly sorts the objects of each class. This sort is called the natural sorting of classes. The compareTo method of classes is called its natural comparison method.

2. The TreeSet Method for Determining the uniqueness of an object is to determine whether the returned result of the comparison method is 0 or 0, which means that the same elements are not stored. In the example, if Person implements the Comparable interface and overrides the compareTo method, and returns 0, no error will be reported during the operation, but only the first element of the memory will be printed, that is: zhangsan, 22, because when the second element is to be stored, the compareTo method is called to determine whether it is the same as the previous element. Because the returned result is 0, it indicates the same, therefore, the following elements are not saved in, so only the first element is printed.

3. Sort the Person objects in ascending order of age.

Implement the Comparable interface of the Person class above, and then overwrite the compareTo method in the Person class.

// If You Want To sort data from large to small, change 1 to-1, change-1 to 1, or change this to p, and change p to this. public int compareTo (Object obj) {Person p = (Person) obj; if (this. age> p. age) return 1; if (this. age <p. age) return-1; return 0 ;}

However, if the age is the same, the last one cannot be printed, that is, one Person is missing during printing.

In this case, the conditions should be added. If the primary conditions are the same, the secondary conditions should be compared.

The modified compareTo method is as follows:

Public int compareTo (Object obj) {Person p = (Person) obj; if (this. age> p. age) return 1; if (this. age <p. age) return-1; The compareTo method in the else/* String class also comes from the Comparable interface. The String class implements the Comparable interface */return this. name. compareTo (p. name );}

However, this write is too bad..., optimization:

public int compareTo(Object obj) {Person p = (Person)obj;int temp = this.age - p.age;return temp == 0 ? this.name.compareTo(p.name) : temp;}

Objects of the String class stored in the TreeSet can be sorted because the String class implements the Comparable interface.

Summary: One of the ways TreeSet sorts elements:

Make the elements have their own comparative functions. The elements need to implement the Comparable interface to overwrite the compareTo method.

16-11, TreeSet set, Comparator

1. What should I do if the object is not in the natural order of nature and the object is not in the natural order?

You can use the second sorting method of TreeSet to make the set itself have a comparison function.

2. The TreeSet constructor has a constructor with the Comparator parameter. When a TreeSet object is created, the Comparator object is input. The TreeSet can be sorted by the specified Comparator.

3. java. util

Interface: Comparator

A comparison function that forcibly sorts the Collection objects.

4. Create a separate Java file and create a comparator sorted by the name of the Person class.

public class ComparatorsByName implements Comparator {public int compare(Object o1,Object o2) {Person p1 = (Person)o1;Person p2 = (Person)o2;int temp = p1.getName().compareTo(p2.getName());return temp == 0 ? p1.getAge() - p2.getAge() : temp;}}

Then, when creating the TreeSet set, directly:

TreeSet ts = new TreeSet(new ComparatorsByName());

You can.

5. If the Person object implements the Comparable interface, overwrite the compareTo method, and saves the Person object to the TreeSet that has implemented the comparator, who will give priority to the comparison function?

The comparator is mainly used, and it is commonly used in actual development.

In fact, many classes in Java implement the Comparable interface so that their objects can be compared.

6. Steps to make the set itself more functional:

Define a class to implement the Comparator interface, override the compare method, and pass the class object as a parameter to the constructor of A TreeSet set.

16-12, TreeSet-Binary Tree

1. How is the TreeSet sorting function implemented at the underlying layer?

Its sorting function is implemented through a binary tree at the underlying layer.

The following example shows how to add a TreeSet in a graph (sorted by age of Person ),

The first element does not need to be compared, and the subsequent elements must be compared with the previous element.


Steps:

After the first 28 came in, we found that there were no elements in the front and we did not compare them. We placed them directly in the first position.

21. After Entering, it is smaller than 28, and placed on the left of 28.

After 29, we first compared it with 28, which is bigger than 28. If we put it on the right side of 28, we don't need to compare it with 21.

After entering 25, compare it with 28, smaller than 28, to the left, and then 21, bigger than 21, and put it on the right of 21.

......

In the tree, each node has its own attributes. For example, a node with a value of 21:


21 there are three references, respectively recording the parent node linked to it, as well as the left and right child nodes, to record the location of each element in the entire set, but 28 has no parent, 19. No left or right.

However, if the size of a tree is large, it involves efficiency. How can this problem be solved?

In fact, as long as a row of trees is complete, the set is already an ordered set. the query of Ordered Sets can be thought of using the binary search method.

In fact, each time an element is added to it, the existing element will be halved and searched in two parts to determine the location of the new element, which is more efficient.

2. How can we save it?

Return 1 directly in the comparator. This ensures that the later elements are always greater than the previous ones after comparison. If you want to retrieve them in reverse order, return a-1 directly.

public class ComparatorsByName implements Comparator {public int compare(Object o1,Object o2) {return 1;}}

16-13, TreeSet exercise

Requirement: sort by string length.

public class TreeSetTest {public static void main(String[] args) {TreeSet ts = new TreeSet(new ComparatorsByLength());ts.add("aaaaaa");ts.add("zz");ts.add("nabq");ts.add("cba");ts.add("abc");Iterator it = ts.iterator();while(it.hasNext()) {System.out.println(it.next());}}}
// Comparator public class ComparatorsByLength implements Comparator {public int compare (Object o1, Object o2) {String s1 = (String) o1; String s2 = (String) o2; int temp = s1.length ()-s2.length (); return temp = 0? S1.compareTo (s2): temp ;}}


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.