Javase Study notes (1)

Source: Internet
Author: User
Tags iterable concurrentmodificationexception

(1) Static import

The import technology is actually in Java for the convenience of using other people to write good classes.

Import java.lang.*| class name

Only classes can be imported in the original Guide package statement. If you need to import some static methods or properties then there is nothing to do.

Example 1: Find the area of a circle of any radius?

Find the area of a circle of any radius

Public Static void Getarea () {

1. Ask for a random radius

double r = Math. Ceil (Math. Random () *10);

2. Calculate area

Double area = 0.0;

Area = Math. PI*r*r;

3. Print Area

System. out. println ("radius is" +r+ "the area of the circle is:" +area);

}

There are a number of static members found in the above code.

You can then use static import to simplify the writing of your code.

Grammar:

Import Static java.lang.*| Member

Actual combat:

Import Static Java.lang.Math. PI ;

Import Static Java.lang.System. out ;

Import Static Java.lang.Math. random;

Import Static Java.lang.Math. ceil;

Public class Demo4 {

Find the area of a circle of any radius

Public Static void Getarea () {

1. Ask for a random radius

double r = ceil(random() *10);

2. Calculate area

Double area = 0.0;

Area = PI*r*r;

3. Print Area

out. println ("radius is" +r+ "the area of the circle is:" +area);

}

}

If you use multiple static members of a class in your code, you can import them all directly using *.

Import static java.lang.math.*;

(2) Variable parameters

Think: If the developer is now defining a function (method), then how to specify the parameter when the number of parameters is not known.

Syntax: Defining the syntax of a function

Modifier returns a value type method name (parameter type ... Variable name) Exception declaration {

function body

Return

}

Note: Learn the nature of variable parameters

    1. A mutable parameter is actually a mutable array.
    2. Mutable parameters can only appear in the last position of the parameter list in the declaration of a method
    3. A mutable parameter can only appear once in the parameter list

Example 1: Calculate the sum of any integers?

The sum of any integers?

Public Static long getsum (int... is) {

long sum = 0;

for (int i = 0; i < is.length; i++) {

Sum +=is[i];

}

return sum;

}

For example, variable parameters in the 2:sun API.

Static <T> list<t> aslist (T ... a) returns a list of fixed sizes supported by the specified array.

U Packing Class

In fact, in Java there are four types of eight basic data type. If all the basic data types are not objects then Java

Language is not a true OOP language.

Wrapper class is a wrapper. In the packaging class, Sun sealed off some of the developers commonly used properties and methods, can be quickly programmed.

Packing class

Basic data types

Byte

Byte

Short

Short

Integer

Int

Long

Long

Boolean

Boolean

Character

Char

Float

Float

Double

Double

Example 1: Experience the properties provided by the integer class.

Experience the properties of the Integr class

Public Static void GetField () {

System. out. println (Integer.    Min_value); -2147483648

System. out. println (Integer.    Max_value); 2147483647

}

Read the following code to analyze the error cause of the code:

Long date = 12345678910; Error

12345678910

2147483647

Example 2: Experience the methods provided by the integer class.

The main learning is the method of converting integers to strings.

How to experience the Integr class

Public Static void GetMethod () {

To create a class object

Integer in1 = new integer (123);

int i1 = In1.intvalue ();

System. out. println (i1+1);

Convert to String

String str1 = in1.tostring ();

System. out. println (str1+1);

}

In fact, there is no need to transition to a string when the basic ToString () call.

Simplify the code above:

How to experience the Integr class

Public Static void getMethod2 () {

To create a class object

Integer in1 = new integer (123);

int i1 = in1; Automatic unpacking

System. out. println (i1+1);

Convert to String

System. out. println (in1+ "" + 1);

}

(3) What is automatic unpacking and automatic packing?

Auto-Boxing: If the base type is passed to the wrapper type. Integer in1 = 12;

Auto-unpacking: If the wrapper type is passed to the base type. int i1 = in1

Useful when generics are:

Collection: The main purpose is to store objects.

List.add (1); Automatic Boxing

thinking: String str = "Hello";

U-Enhanced for loop

If you want to traverse a specified number, we typically use a traditional for loop.

Grammar:

for (conditional initialization statement; conditional expression; loop increment) {

Loop body break or continue

}

If you write this way, you will encounter an exception that crosses the subscript every time.

Therefore, you can use the enhanced for loop for fast traversal (arrays, collections, and classes that implement the Iterable interface).

Grammar:

For (data type variable name: Collection to traverse) {

Loop body

}

Example 1: Traverse a normal array.

Iterate over an array

Public  Static void printArray (int [] a) {

for (int temp:a) {

System. out. println (temp);

}

}

Example 2: Traversing a list collection.

Traverse a list

Public Static void printlist (list<string> List) {

for (String string:list) {

System. out. println (string);

}

}

Example 3: Traverse a Map collection.

Traverse a Map collection

Public Static void Printmap (map<integer,string> Map) {

You want to convert it to a set class that implements the iterable interface

Set<map.entry<integer, string>> set = Map.entryset ();

Traversing set Collection

for (Map.entry<integer, string> entry:set) {

Gets the key and value values of the entry object

Integer key = Entry.getkey ();

String value = Entry.getvalue ();

System. out. println (key+ "=" +value+ ",");

}

}

Think: If the above collection does not use generics, what type should be used to receive collection data when using the For loop? Object

Question 1: Can I change the data in the collection using the enhanced for loop?

Because the For loop uses a copy of the value to a temporary variable when it is traversed. Therefore, changing the TEMP variable does not change the data value in the collection.

2: The problem of manipulating the collection when using the enhanced for loop traversal collection?

Traverse a list

Public Static void printlist (list<string> List) {

for (String string:list) {

List.add ("eeee"); Run error

System. out. println (string);

}

System. out. println ("in Traversal:" +list);

}

The exception information is as follows:

Exception in thread "main" java.util.ConcurrentModificationException

Simulated basic classes have seen the scene:

Public Static void Main (string[] args) {

list<string> list = new arraylist<string> ();

List.add ("AAAA");

List.add ("bbbb");

List.add ("CCCC");

List.add ("dddd");

Iterator<string> it = List.iterator ();

while (It.hasnext ()) {

List.add ("yyyy");

String str = It.next ();

System. out. println (str);

}

}

Run Exception:

Exception in thread "main" java.util.ConcurrentModificationException

Summary

Iterators are used by default when iterating over collections using the enhanced for loop, so you cannot use the collection's reference variables to manipulate the collection directly in the loop to avoid security exceptions that result in multithreaded concurrent access.

U-Safe Enumeration Classes

In the actual development of the project we often need a class of data, the value of this class of data is a specific range of a set of values. Such as:

Gender: [Male, female]

Traffic lights: [Red, yellow, green]

Day of the week: [One ~ seven]

The above set of values can be defined as enumerated data types.

Grammar:

modifier enum Enum class name {

Defines a set of values for an enumeration, separated by commas between multiple values

}

Realize:

Public enum Gender {

MALE,FEMALE;

}

Question: What is the nature of enumerations?

  1. Enumeration Essence is a class
  2. Inherit from enum class by default
  3. The essence of the enumeration value is the static constant value of the enumeration class
  4. Enumeration values are initialized in a static code block
  5. The default constructor for an enumeration class is parameter-only and private
  6. Enumeration is a singleton pattern
  7. Now that the enumeration is a normal class, our developers can define the members of the class (attributes, constructors, functions) in the class.

    Example 1: Define the attribute in the enumeration.

    Public enum TrafficLight {

    Defining enumeration values

    RED,GREEN,YELLOW;

    Defining member properties

    Public String info = "Traffic light Information";

    Public Static void Main (string[] args) {

    System. out. println (TrafficLight. GREEN. info);

    }

    }

    Example 2:: Defines a constructor in an enumeration.

    Public enum TrafficLight {

    Defining enumeration values

    RED ("Red light"),Green("green light"),YELLOW("Yellow lamp");

    Defining member properties

    Public String info = "Traffic light Information";

    Provides constructors for initialization of properties

    Private TrafficLight (String info) {

    this. info = info;

    }

    Public Static void Main (string[] args) {

    System. out. println (TrafficLight. GREEN. info);

    System. out. println (TrafficLight. RED. info);

    System. out. println (TrafficLight. YELLOW. info);

    }

    }

    Remember that to ensure that enumerations are singleton, the constructors are all private.

    Example 3: Define the function in the enumeration.

    Public enum TrafficLight {

    Defining enumeration values

    RED ("Red light") {

    @Override

    Public void showmessage () {

    System. out. println ("Red Stop!");

    }

    },

    GREEN ("green light") {

    @Override

    Public void showmessage () {

    System. out. println ("Green Line!");

    }

    },

    YELLOW ("Yellow Light") {

    @Override

    Public void showmessage () {

    System. out. println ("You can do it yourself!");

    }

    };

    Defining member properties

    Public String info = "Traffic light Information";

    Provides constructors for initialization of properties

    Private TrafficLight (String info) {

    this. info = info;

    }

    Provide a way to indicate the information of a lamp

    Public Abstract void showmessage ();

    Public Static void Main (string[] args) {

    System. out. println (TrafficLight. GREEN. info);

    System. out. println (TrafficLight. RED. info);

    System. out. println (TrafficLight. YELLOW. info);

    TrafficLight. RED. ShowMessage ();

    }

    }

    The above code can be seen in an enumeration class that defines an abstract method, but cannot declare an enumeration class as an abstract class, only implementing all abstract methods (anonymous inner classes) when declaring enumeration values.

    In the actual enumeration, in fact, the custom enum class inherits the Enum class by default, then we have the defined properties and methods in the Enum class in our enumeration class.

    Common methods

    Description of the method

    String name ()

    Gets the name of the enumeration value

    int ordinal ()

    Returns the ordinal of an enumeration value definition

    ValueOf (class<t> enumtype, String name)

    Finds the enumeration value of the specified name in the specified class by reflection

    VALUES ()

    This method is not visible in the API but is available

    Example 3: Use the methods commonly used in the Enum class.

    Common ways to experience

    System. out. println (TrafficLight.   YELLOW. Name ()); YELLOW

    System. out. println (TrafficLight.   RED. Ordinal ()); 0

    System. out. println (TrafficLight. ValueOf(trafficlight. Class, "GREEN"));

    The methods above are all visible in the API, but there are methods that are not seen in the API but are actually defined internally.

    Example 4: Iterate through the enumeration values.

    Traversing enumeration values

    TrafficLight [] trans = TrafficLight. Values ();

    for (TrafficLight Temp:trans) {

    System. out. println (temp);

    }

Javase Study notes (1)

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.