java. Foundations, collections, enumerations, generics,

Source: Internet
Author: User
Tags float double naming convention set set wrapper

1, MyEclipse installation and use * Eclipse: is a free development tool * MyEclipse: is a charge plug-in, crack myeclipse, * * Installation directory Requirements: cannot have Chinese and space * * Installation completed After selecting a workspace, this workspace cannot have Chinese and white space * crack myeclipse * * Run Run.bat file, but before running, you must install the JDK by configuring the environment variable * MYECLIPSE use * to create a Project-type Java Project Web project-Choose a dependent JDK that can use the JDK that comes with myeclipse, or you can use the installed JDK * to create Package Package-cn.itcast.test XX. Xx.                  XX * Create a class-class naming convention in the package: * * Capitalize the first letter for example: TestDemo1 Usermanager            * Create method in class public void test1 (argument list) {method body or return value; }-the naming convention of the method first letter lowercase example: addnum () * Define variable-variable naming specification * * First letter lowercase, section Capitalize the first letter of two words, such as userName * These names also have a way * * use Hanyu Pinyin to name Yonghuming Mima * * cannot mix Hanyu Pinyin and English letters to make      The most basic principle of naming with userming *: See the name know what it means * code needs to have indentation * Run the program as Java application          Debug as Java application 2 debugging mode (Breakpoint debug mode) * Use this mode, debug the program (see the changes in the program data) * Use the first step of debug need to set a breakpoint (let the program run stop in this Row)-Show line number-double-click to the left, a dot appears, indicating that a breakpoint is set * using Debug as mode, run program-prompt to enter the debug interface, yes-at the breakpoint that one, there is a green bar, Indicates that the program stopped in this line, did not run down * can let the program down,-using step over shortcut is F6 (step)-Resume F8: Indicates the end of debugging, run directly down * * such as the current Breakpoint, and jumps to the next breakpoint, * * If there is no breakpoint after the current breakpoint, the program runs the end * Debug another use * * To view the source code of the program * * F5 Step into: Enter Method * * F7 Step return: Returns 3, myeclipse use * code hint ALT/* Quick Guide Package CTRL shift O * Single Comment CTRL/* minus single line Comment Ctr L/* Multi-line Comment Ctrl shift/* Remove Multiline Comment Ctrl shift * Delete Row Ctrl d 4, junit use * unit Test * Test object is a method in a class * Juint not Part of Javase, want to use import jar Package * * However, the jar package with JUnit in MyEclipse * First JUnit version 3.x 4.x * unit test method, method naming rule public vo The ID Method name () {} * uses annotations to run the test method, above the method * * @Test: Represents the method for unit testing---@Test public void testadd 1 () {TesTjunit test01 = new Testjunit ();            Test01.testadd (2, 3); -Check the method name, right-click Run as---junit test-when a green bar appears, indicating that the method test passed-when a red-brown bar appears, indicating that the method test does not pass-        --To run multiple test methods in the class, click elsewhere in the class, run as---junit Test * * @Ignore: This method is not unit tested * * @Before: Run at each method execution  * * @After: Run * * Assertion after each method (understanding)-assert.assertequals ("Test expected value", "actual value of Method run") jdk5.0 new features JDK 1.1        1.2 1.4 5.0** Generic, enumeration, static import, auto-unpacking, enhanced for, variable parameter * * Reflection 5, Generics Introduction * Why use generics? -Generally used on the set * * For example, now put a value of a string type into the collection, this time, this value into the collection, the loss of the ability of the type, can only be the object type, this time, such as want to type conversion of this value, it is easy to type conversion error, how to solve    This problem, you can use generics to solve * How to use generics on the collection-common collection list set map-generic syntax collection <String> such as List<string>             * In generics the write is an object, String cannot write basic data type such as INT (* * * * * *) write basic data type corresponding wrapper class byte--byte short--short  INT--Integer long--long float--float double--double           CHAR--Character Boolean--Boolean * Three implementations of the generic list on the list ArrayList LinkedList Vect or code: @Test public void Testlist () {list<string> List = new Arraylist<string&gt            ;();            List.add ("AAA");            List.add ("BBB");             List.add ("CCC");                 There are several ways to traverse the list collection three//general for loop iterator enhancement for//normal for loop for (int i=0;i<list.size (); i++) {                String s = list.get (i);            System.out.println (s);            } System.out.println ("=================");            Use the enhanced for (String s1:list) {System.out.println (S1);            } System.out.println ("=================");            Use iterators to traverse iterator<string> it = List.iterator ();            while (It.hasnext ()) {System.out.println (It.next ()); } * Job 1:arraylist LinkedList Vector These three differences * in SUse generic code on ET://generics using Set set @Test public void Testset () {set<string> set = new            Hashset<string> ();            Set.add ("www");            Set.add ("QQQ");            Set.add ("zzz");            Set.add ("QQQ"); There are several ways to traverse set: two//Iterator enhancements for//use enhanced for traversal for (String s2:set) {System.            OUT.PRINTLN (S2);            } System.out.println ("=================");            Use an iterator to traverse iterator<string> it1 = Set.iterator ();            while (It1.hasnext ()) {System.out.println (It1.next ()); }} * Use generic-map structure on map: Key-valu form code://Use generics @Test public void Te on map            Stmap () {map<string,string> Map = new hashmap<string,string> ();            Map.put ("AAA", "111");            Map.put ("BBB", "222");            Map.put ("CCC", "333"); There are several ways to traverse the map in two//1, the obtainedTake all keys, get value by key using the Get method//2, get the relationship between key and value//use the first way to traverse//Get all key set&lt ;            string> sets = Map.keyset (); Iterates over all keys returned by the set for (String key:sets) {//by key to get value String value = Map.get (k                EY);            System.out.println (key+ ":" +value);            } System.out.println ("==============");            Get the relationship between key and value set<entry<string, string>> sets1 = Map.entryset (); Traverse Sets1 for (entry<string, string> entry:sets1) {//entry is key and value relationship S                Tring Keyv = Entry.getkey ();                String Valuev = Entry.getvalue ();            System.out.println (keyv+ ":" +valuev); }} 6, generics use the method to define an array, to implement the exchange of the array elements at the specified location * method logic is the same, but the data type is different, this time using a generic method */* * Using a generic method needs to define a type using uppercase letters to denote T : This t means that any type * is written before the return value before void <T> * ======= indicates that a type is defined and this type is T * You can use this type below: T */public static <T> void Swap1 (t[] arr, int a,int b) {T temp = arr[a];        Arr[a] = arr[b];    ARR[B] = temp; } * * Job 2: Implement a generic method, accept any array, invert all elements in the array 7, generics use on the class (understand) * Define a type on a class that can be used directly within the class * public class Testdemo04<t    > {//In the class can directly use T's type T AA; public void test11 (T bb) {}//write a static method on a generic type defined above the class, no longer static method inside use public static <A> void test12 (A cc) {}} 8        , Introduction to Enumerations * What is an enumeration?        * * need to be in a certain range of values, this value can only be any one of the range.    * * Real scene: traffic lights, there are three colors, but each can only light three colors inside of any one * use a keyword enum * * enum Color3 {red,green,yellow; The construction method of the enumeration is also private * Special enumeration operations (understanding) * * There are constructor methods inside the enumeration class * * Constructor method has parameters inside, need to write arguments on each instance * * in enum class There is an abstract method * * In the enumeration Each instance overrides this abstract method 9, an enumeration of the API's operations * * Name (): Returns the name of the enumeration * * Ordinal (): Subscript of the enumeration, subscript starting from 0 * * VALUEOF (class<t> enumtype, Str ing name): The object that gets enumerated * * There are two methods, both of which are not in the API, compile two methods * * * * * * * valueof (String name) Conversion Enumeration Object * * * VALUES () Get all enumerated objects Group    * Exercise: Enumerating objects, enumerating object subscripts, converting between enumeration object name representations-//knowing enumerated objects, getting enumeration names and subscripts @Test public void test1 () {//Get enumerated object Color        C100 = color100.red;        Enumeration name String name = C100.name ();        enum subscript int idx = c100.ordinal ();    System.out.println (name+ "" +idx);        }-//Know the name of the enumeration, get the enumerated object and subscript @Test public void test2 () {String name1 = "GREEN";        Get Object Color100 c1 = color100.valueof (name1);        enumeration subscript int idx1 = c1.ordinal ();    System.out.println (IDX1);        }-//Know the subscript of the enumeration, get the object and name of the enumeration @Test public void Test3 () {int idx2 = 2;        The object that gets the enumeration color100[] cs = color100.values ();        Get the object Color100 C12 = cs[idx2] according to subscript;        Gets the name of the enumeration String name = C12.name ();    SYSTEM.OUT.PRINTLN (name);    } 10, static import (understanding) * Can be in the code, directly using static Import method, import static methods or constants * Import static XX.XX.XXX * import static java.lang.System.out;     Import static Java.util.Arrays.sort;  * * For example, now implement a calculator in the Math class 11, automatic unboxing  * Boxing * * Converting basic data types into wrapper classes * Unpacking * * Converting wrapper classes to basic data types *//auto-boxing Integer i = 10;         Automatic unpacking int m = i; * * in jdk1.4 How to implement boxing and unpacking-//in jdk1.4 inside implement unboxing public void Test1 () {//boxing Integer m = new in                   Teger (10);        unboxing int a = M.intvalue (); * * JDK is backwards compatible-like the code written in jdk1.4, this time to 5.0 can also run * * Exercise: backward compatibility = = Execution result is called dosomething (double m) = = First In jdk1.4 inside must call this method, if call the following method, need type conversion, but jdk1.4 cannot implement automatic unboxing = = because the JDK is backwards compatible, so, in jdk1.4 call this method, in jdk5.0 still will call this method public STA         tic void Main (string[] args) {dosomething (10);        public static void DoSomething (double m) {System.out.println ("double ...");        public static void DoSomething (integer a) {System.out.println ("integer ..."); * * Remember: eight basic data types corresponding to the wrapper class * int---Integer * char---Character 12, enhanced for loop (* * * * *) * syntaxFor (traversed value: the collection to traverse) {}-for (String s:list) {System.out.println (s); } * Use scene: Array; A collection that implements the Iterable interface can use the enhanced for loop * to traverse the list set using the enhanced for loop on the collection to implement the Iterator interface, so you can use the enhanced for loop map without        You can use the enhanced for loop without implementing the iterator interface, so you cannot use the enhanced for loop * to enhance the For loop appearance purpose: In order to replace the iterator * * Enhanced for the bottom is the iterator implementation of 13, content Supplement (1) Generic erase  * First generics only appear in the source code stage, and the generics do not exist after compilation (2) Exercise: Implement a generic method that accepts an array of any type, reverses all element codes in the array public static <T> void reverses (t[]         ARR1) {/* * basic idea: The first element and the last element exchange position, the second element and the reciprocal second element exchange position ....            * Swap Length/2 * *//traverse array for (int i=0;i<arr1.length/2;i++) {/*int temp = arr1[0];            Arr1[0] = arr1[arr1.length-1];*/T temp = arr1[i];            Arr1[i] = arr1[arr1.length-i-1];        ARR1[ARR1.LENGTH-I-1] = temp; }} 14, variable parameters * variable parameters can be applied in what scenario: * * To achieve the addition of two numbers, to achieve the addition of three number of four number of addition--if the implementation of multiple methods, the logic of these methods is basically the same, the only difference is the number of parameters passed, you can make Define method data type with variable parameter * variable parameter ... The name of the array * is understood as an array, this arrayStore passed arguments-code public static void Add1 (int ...            Nums) {//nums is understood as an array, this array stores the parameters passed over//system.out.println (nums.length);            int sum = 0;            Iterate over array for (int i=0;i<nums.length;i++) {sum + = nums[i];        } System.out.println (sum);            * Note where (1) mutable parameters need to be written in the parameter list of the method and cannot be defined separately (2) in the parameter list of the method can only have a variable parameter in the parameter list of a variable parameter (3) method, which must be placed at the end of the argument -ADD1 (int a,int ... Nums) 15, the principle of reflection (******** understanding ********) * Applied in some high-versatility code * The framework, most of which is implemented using reflection * in the framework development, is based on the configuration file development * * In the configuration text A class is configured in a piece, you can get all the content in the class by reflection, and you can have a method in the class that executes all the contents of the * Class: Properties, constructor without parameters, constructor method with parameters, general method * Principle of drawing analysis reflection * First, you need to save the Java file to         Local hard disk. java * Compiles Java files into a. class file * Using the JVM to load class files into memory through the classes * Everything is an object, class files are represented in memory using class classes * When using reflection, you first need to get to the class, get this class, you can get all the contents of the class file-including property construction method Ordinary method * Property through a class Filed * construction method through a Class Constructor * Common method through a class method 16, theUsing the parameterless construction method inside the Reflection Operation class (* * will write * *) * First get to class-//Get class class clazz1 = Person.class;        Class clazz2 = new Person (). GetClass ();     Class clazz3 = Class.forName ("Cn.itcast.test09.Person");        * For example: to instantiate a class, you can new, do not use new, how to get?        -//Get Class class C3 = Class.forName ("Cn.itcast.test09.Person");    Get an instance of the person class person P = (person) c3.newinstance (); * Code//Operation parameterless construction method @Test public void Test1 () throws Exception {//Get class class C3 = Class.forName ("        Cn.itcast.test09.Person ");        Get an instance of the person class person P = (person) c3.newinstance ();        Set the value p.setname ("Zhangsan");    System.out.println (P.getname ()); } 17, using the reflection operation has the parameter construction method (* * will write * *)//operation parameters of the construction method @Test public void Test2 () throws Exception {//Get class Cla        SS C1 = Class.forName ("Cn.itcast.test09.Person"); Use the constructor method with parameters//c1.getconstructors ();//Get all the construction methods//Pass is the constructor method with parameters inside the parameter type, type is passed Constructor cs in class form C1.getconstructor (String.class,string.class);        Set the value through the constructor of the parameter//create a person instance with the constructor of a parameter person P1 = (person) cs.newinstance ("Lisi", "100");    System.out.println (P1.getid () + "" +p1.getname ()); } 18, use the Reflection Action property (* * Will write * *) *//Operation Name property @Test public void Test3 () {try {//Get class Clas            s C2 = class.forname ("Cn.itcast.test09.Person"); Get the name attribute//c2.getdeclaredfields ();//To get all the attributes//Get the instance of the person class person P11 = (person) C2.N            Ewinstance ();            The property is obtained by this method, the parameter is the name of the property Field F1 = C2.getdeclaredfield ("name");            Operation is private property, do not let operation, need to set can manipulate private property setaccessible (True), can manipulate private property f1.setaccessible (True); Set the name value set method, two arguments: an instance of the first argument class, the second parameter is the value set F1.set (P11, "Wangwu");            Equivalent to P.name = "Wangwu"; System.out.println (F1.get (P11));        Equivalent to P.name}catch (Exception e) {e.printstacktrace (); }} 19, use generic operation Common method (* * Write * *) * use meThe Thod class represents the normal method * Code//Operation common method, such as Operation SetName @Test public void Test4 () throws Exception {//Get class        Class C4 = class.forname ("Cn.itcast.test09.Person");        Get person Instance person P4 = (person) c4.newinstance (); Get the Common Method//c4.getdeclaredmethods ();//Get all the common methods//pass two parameters: first parameter, method name, second argument, method inside parameter type method m1 = C4.get        Declaredmethod ("SetName", String.class); Let the SetName method execute, execute the Setting value//use Invoke (P4, "Niuqi"), pass two parameters: first argument, person instance, second parameter, set the value//after executing the Invoke method, equivalent to executing the Setnam        E method, at the same time set a value by this method is Niuqi M1.invoke (P4, "Niuqi");    System.out.println (P4.getname ());     } *//Operation private method, need to set value is True *//m1.setaccessible (TRUE); * When the method of operation is static method, because the static method is called by the class name. Method name, no instance of class * Use reflection operation static mode, also do not need instance * in the first parameter of the Invokie method, write a Null-m1.invoke ( NULL, "Niuqi");

java. Foundations, collections, enumerations, generics,

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.