Java programming ideas object set (array, list, set, MAP) 1

Source: Internet
Author: User
Tags addall

1,Arrays class: Provides some static methods for operating arrays, such

Fill () is used to fill the entire array with a value.

Sort () is used to sort arrays and requires parameter type implementation.ComparableInterface

Binarysearch () is used to search for elements in sorted arrays.

Aslist () accepts any array as a parameter and converts it to a list container.

......

2. If a string needs to change its value multiple times, use stringbuffer to replace string more efficiently.

3. Copy the array system. arraycopy (), and use it to copy the array is much faster than using for loop replication.

4. Both the basic type array and the object array can be copied. However, if the object array is copied, the object reference is copied instead of the object itself. This is called "shortest copy ".

5,Array comparison:

Arrays .equal()

import java.util.Arrays;public class Test{   public static void main(String[] args){      String[] s1 = new String[5];      Arrays.fill(s1,"Hi");      String[] s2 = {"Hi", "Hi", "Hi", "Hi", "Hi"};      System.out.println(Arrays.equals(s1, s2));      System.out.println(s1.equals(s2));      System.out.println(s1==s2);   }}

1). For arrays.Equals, S1, so the element points to the same object, and array S2 contains five mutually independent objects. However, the array is equal based on the content (through the object. equal () comparison), so the result is true.

2). But the input of the last two statements isFalse. Why?

6,Comparison of array elements:

1) Java has two methods to provide the comparison function. The first method is to implement the java. Lang. Comparable interface, which contains onlyCompareto (Object O)A method.

2) Implement the comparator interface. There are two methods in the zone.Compare (Object O1, object O2)AndEquals (Object O)Two methods.

7. java standard library: "Quick Sort" designed for basic types and "stable merge sort" designed for objects ".

8. If the target is found, the returned value of arrays. binarysearch () is equal to or greater. Otherwise, it generates a negative return value, indicating thatKeep the array sortedThe position where the target element should be inserted. The negative value calculation method is as follows:

-(Insert point)-1;

Insert pointIndicates the position of the first element greater than the search object in the array. If all the elements in the array are smaller than the objects to be searched, the "insert point" is equal to the size () of the queried array ().

If the array contains repeated elementsWhich one cannot be found?. This algorithm is indeed not designed for arrays containing duplicate elements, but is still available.

If you wantArray sorting without repeated Elements, You can useTreeset(Keep the array order), orLinkedhashset(Keep insertion order ..

9. You cannot use comparator to sort basic data arrays.

10. When using binarysearch (), you must provide the same comparator (the overloaded version of the method used ).

11. arrays are the most efficient groups.ObjectIt is your first choice. And,If you want to save basic types, you can only use arrays.

12. The purpose of the Java container class library is"Save object", And divide it into two different concepts:

1). collection. An independent element that complies with one or more rules. ListThe specific sequence of elements must be saved.And setDuplicate elements are not allowed..

2). Map. A pair"Key-value pairs"Object. It seems that this should be a collection, and its elements are paired objects. However, this design is too clumsy, So we extract the map explicitly to form an independent concept. On the other hand, if you use collection to represent part of the map content, it is easy to view this part of content. ThereforeMap returns the set composed of all keys., A collection composed of all values, or a set composed of its key-value pairs;And it is easy to expand to multiple dimensions like arrays.Map, no need to add new concepts,You only need to make each "value" of the key-value pair in the map a map (the "value" in this map can also be map, and so on ).

13,

1). List stores objects in the order they enter, without sorting or editing.

2 ).Set only accepts each object once and uses its internal sorting method(Generally, you only care about whether an element belongs to the set but not the order of the element -- otherwise, you should use list ).

3). MAP also saves a copy of each element, but this is based on the "key,MAP also has built-in sortingAnd does not care about the order in which elements are added.

4 ).If the order of adding elements is important to you, use javashashset or javashashmap .,

14. The fill () method in collections also copies the reference of the same object to fill the entire container.List objectUseful.

15. disadvantages of containers: when an object is added to a containerThe type information is lost.. The container only saves the reference to the object. The object is the base class of all classes, so the container can save any type of objects. (Basic types are not included, because they are not real objects and do not inherit anything .)

16. If arraylist was originally used, but the set should be used in consideration of the characteristics of containers, what should we do? Or you want to write general-purpose code. They only use containers and do not know or care about the container type,So how can we apply different types of containers without rewriting the code?

Iterator(Also a design pattern) can be used to achieve a secondary goal.An iterator is an object.It traverses and selects objects in a sequence, and the client programmer does not have to know or care about the underlying structure of the sequence (That is, the types of different containers.). In addition, the iterator is often called"Lightweight"Object: it is easy to create.

17. The collection does not include the get () method for Random Access to the selected element. Because collection includes set, set maintains the internal order by itself (which makes random access meaningless ).Therefore, if you want to check the elements in the collection, you must use the iterator.

18. In Java, vector, stack, and hashtable are outdated.

19. Functions and methods of list

If the performance overhead is mainly produced by other factors in the development environment, the overhead difference between arraylist and javaslist is not important, no matter which one can be used.

20. Functions and methods of set:

Set has the same interface as collection, so there is no additional function. Set is actually a collection, but the behavior is different. (This is a typical application of inheritance and Polymorphism: different behavior .) Set does not save repeated elements.

Import Java. util. arrays; import Java. util. hashset; import Java. util. linkedhashset; import Java. util. set; import Java. util. treeset; public class testset {static void fill (set <Object> S) {// split the string based on the matching regular expression. S. addall (arrays. aslist ("One two three four five six seven ". split ("");} public static void text (set <Object> S) {// replaceall (string RegEx, string replacement) // replace all the substrings matching the given regular expression with the given replacement. System. out. println (S. getclass (). getname (). replaceall ("\ W + \\. "," "); // call multiple times: to verify that the set does not save duplicate elements. Fill (s); fill (s); system. out. println (s); S. addall (s); S. add ("one"); S. add ("one"); S. add ("one"); system. out. println (s); system. out. println ("s. contains (\ "one \"): "+ S. contains ("one");} public static void main (string [] ARGs) {text (New hashset <Object> ()); text (New treeset <Object> (); text (New javashashset <Object> ());}}

Running result:

From the running results, we can note that the order of elements maintained by hashset is different from that maintained by treeset and javashashset, because they save elements so that they can be found in different ways later.

1). treeset usesRed/black treeData Structure sorting element.

2) hashset usesHash FunctionThis is specially designed for quick query 2.

3). Internal use of linedhashsetHashAccelerate query and useLinked ListMaintain the order of elements.

20. When hashset and treeset are used, equals () must be defined for the class, while hashcode (), it is necessary only when the class is used by hashset (this is very likely becauseHashset is usually the first choice to use set.). In any case, as a programming style,When equals () is overwritten, hashcode () should be overwritten at the same time ().

21. Functional methods of MAP:

"Key" must be uniqueWhile "value" can be repeated.

import java.util.HashMap;import java.util.Map;import java.util.Random;class Counter{   int i = 1;   public String toString(){      return Integer.toString(i);   }}public class Statistics{   private static Random rand = new Random();   public static void main(String[] args){      Map<Object, Object> m = new HashMap<Object, Object>();      for(int i = 0; i < 10000; i++){        Integer r = new Integer(rand.nextInt(20));        if(m.containsKey(r)){           ((Counter)m.get(r)).i++;        }        else{           m.put(r, new Counter());        }      }      System.out.println(m);   }}

Here, why not use integer instead to write another counter class?

Cause:Once an object of the Java Wrapper class (such as the integer here) is created, its value cannot be changed.

Downlink:

Java programming ideology object set (array, list, set, MAP) 2

The above content is compiled from Java programming ideas. If any omission exists, please leave it blank!

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.