The wish to write a technology blog every week has never come true , Starting this week, every Friday night 10 It's time to blog

OOP One of the most important characteristics of the Internet is polymorphism , There are many ways to achieve polymorphism . example : heavy load overload、 rewrite overwite、 Interface oriented programming and so on . However, overloading should be used with caution in practical application , This is also Effective Java One of the things mentioned in . Let's show it first eJava The code mentioned in :

@Test

public void testOverWrite(){

List<Integer> intList = new ArrayList<Integer>();

Set<Integer> intSet = new HashSet<Integer>();



for(int i = -3 ; i < 3 ; i++){

intList.add(i);

intSet.add(i);

}

System.out.println(intList+" ---> "+intSet);



for(int i =0 ; i< 3 ;i++){

intList.remove(i);

intSet.remove(i);

}



System.out.println(intList+" ### "+intSet);



}

Suppose there is no test Many people may think that the output is like this :

[-3, -2, -1, 0, 1, 2]  --->  [0, 1, 2, -3, -2, -1]

[-3, -2, -1] ###  [-3, -2, -1]

But it turns out that :

[-3, -2, -1, 0, 1, 2]  --->  [0, 1, 2, -3, -2, -1]

[-2, 0, 2]  ###  [-3, -2, -1]

The first line must be OK ,intSet Also no problem .intList Maybe a lot of people will have questions ‘’ Why with intSet It's different. ‘

In fact JDK5 I didn't have that problem before ,jdk5 And later added their own active packaging box function , The basic type and the reference type will help you to convert .

This leads to List stay remove It's the index that's removed when it's done , Instead of the data in the container you think .

public E remove(int index) {

        rangeCheck(index);





        modCount++;

        E oldValue = elementData(index);





        int numMoved = size - index - 1;

        if (numMoved > 0)

            System.arraycopy(elementData, index+1, elementData, index,

                             numMoved);

        elementData[--size] = null; // Let gc do its work





        return oldValue;

    }

Instead of this function :

public boolean remove(Object o) {

        if (o == null) {

            for (int index = 0; index < size; index++)

                if (elementData[index] == null) {

                    fastRemove(index);

                    return true;

                }

        } else {

            for (int index = 0; index < size; index++)

                if (o.equals(elementData[index])) {

                    fastRemove(index);

                    return true;

                }

        }

        return false;

    }

jdk I took the initiative to help you unpack . and HashSet No, remove The index method is called remove object

public boolean remove(Object o) {

        return map.remove(o)==PRESENT;

    }

So there won't be list That kind of question .

So when List remove One Integer You need to pay attention to , It's very likely that it doesn't turn out to be the function you want .

------------------------- Beautiful cutting line ——————————————————

Two 、 When the parameter list is similar , It's better not to use overloading . In particular, exporting public API. most easy yes Users Cause confusion . Like the one I met today Money Class has two functions with the same parameter list :multiply and multiplyBy, Have the same parameter list . The first time I used it, I followed in and opened the code , Keep sth. in mind multiply Inside is the new new I got an object , The value of the original object remains unchanged . Also understand that this value cannot be changed . But the line code was optimized before the launch , Used ’multiply‘. Only the first half of the test was followed up , It turns out that the data is right . It turns out that at the end of the day there's another problem , It turns out that multiplyBy, And the function changes the original object . A waste of time . Why not write the full name ? A function name can probably use at most 65535 Character length , It seems that no matter how complex the business function name is, it can't be so long .

———————— Gorgeous cutting line ————————————————-———

3、 ... and 、 Observation Code :

private static void printClassName(Set<?> set){

System.out.println(set.getClass().getSimpleName());

}

private static void printClassName(List<?> list){

System.out.println(list.getClass().getSimpleName());

}

private static void printClassName(Collection<?> col){

System.out.println("unknow class name...");

}

public static void main(String[] args) {

String[] str = {"a","b"};

Collection<Integer>[] cols = {

new HashSet<Integer>(),

new ArrayList<Integer>(),

new HashMap<Integer,Integer>()

};

for(Collection col : cols){

printClassName(col)

}

}

overwiter Is implemented between parent and child classes ,overload Is implemented in the same class . therefore overload It's the compile time . Which method to call depends on the type of reference . So the above three times will print ’unknow class name‘. Due to compiler col All are collection Type of .

and overload The method is selected according to the type of the instance of the class in which the method is called , So we will use the duplicated implementation in the subclass .

Effective_java The second : Use overloaded functions with caution

  1. 【C++ Note 3 for beginners 】 Dummy functions 、 Default parameters 、 Inline function ( Module two ,PS: You need to use overloaded functions )

    One , Dummy functions : If a function parameter has only type but no name, it is called dummy element . Be similar to void fun(int); function :1 Keep forward compatibility , Let's say we need to make a finished product , And then the finished product will be constantly updated, the first generation and the second generation , When we ...

  2. C++ Learning notes ( Twelve ): overloaded function

    1.  What are overloaded functions Suppose that several functions in the same scope have the same name but different parameter lists . So these functions are called -- overloaded function . such as : void print( const char *cp); void print(co ...

  3. C++ Class polymorphism 2 ( function overloading -- Function rewriting -- Function redefinition )

    // function overloading -- Function rewriting -- Function redefinition #include<iostream> using namespace std; /* function overloading : It has to be done in a class ( A subclass cannot overload a function in a parent class ) Son ...

  4. C++ Learning basics 12 —— Pure virtual functions and abstract classes

    One .C++ Pure virtual functions and abstract classes : 1. A class containing one or more pure virtual functions becomes an abstract class , Note that this is a pure virtual function , Instead of virtual functions . 2. If a subclass inherits an abstract class , Must implement the pure virtual function in the parent class , Otherwise, the class is also an abstract class . 3. If one ...

  5. C++: Operator overloading friend operator overloading of function

    5.2.2 Friend operators overload functions Operator overloaded functions are generally defined in two forms : One is defined as the member function of the class it will operate on ( Short for operator overload function ): The second is defined as the friend function of a class ( Friend operator overloaded function for short ). 1. Define friend operations ...

  6. c++ Choose overload function

    One . function overloading The key of common function overload is parameter list --- It is also called function characteristic mark . Overloads can occur in function arguments in the following cases : 1.  The number of formal parameters is different 2.  The types of formal parameters are different 3.  The type and number of formal parameters are different const Parameters and functions are repeated ...

  7. Spline Spline function //C++ keyword :operator // overloaded function // The implicit this The pointer // Pointers and const qualifiers

    In numerical analysis of Mathematics , Spline is a special function , Defined by polynomial segments . Spline interpolation is a form of interpolation using a special piecewise polynomial called spline . Because spline interpolation can use low order polynomial spline to achieve small difference error , This avoids the use of higher-order polynomials ...

  8. Dynamic object creation ( Two ) heavy load new and delete

    Dynamic object creation ( Two ) heavy load new and delete Preface Above, I briefly introduced the method of creating dynamic objects , This article is mainly about overloading new and delete Do some explaining , I also hope to get the advice from my friends , Thank you very much . Usually ...

  9. 《 Challenge 30 God C++ Entry limit 》C++ Using constructor and nameless object to simplify operator overloading function

        C++ Using constructor and nameless object to simplify operator overloading function Before you fully describe the idea , Let's take a look at the following example first , The overload of the addition operator in this example is in the form of a non member function : // Program author : Guan Ning   // Site :www.cn ...

Random recommendation

  1. git mac The client uses commit and sync

    Click on file -> add local  repository Put the local existing git Add library to client When the project changes , Click on the center above Uncommitted Change Button to see what's changed stay ...

  2. dom4j How to parse XML file

    Recently Some are right xml Operation of file , Here's a simple one dom4j analysis xml File and encapsulate it into a javabean Examples in , It's just targeted , It's not universal , For reference only ~~ The first said :dom4j It's a java Of XML ...

  3. array_unshift() 、

    Definition and Usage array_unshift() Function inserts one or more elements at the beginning of an array . The added elements are added as a whole , These elements are in the same order in the array as they are in the parameters . This function returns the number of elements in the array . grammar arr ...

  4. [.NET Field driven design practice series ] Topic 6 :DDD Practical cases : The realization of online bookstore order function

    One . introduction The last topic has realized the shopping cart function for the online bookstore , In this topic , Will continue to improve the online bookstore case , This topic will introduce the realization of online bookstore order function , Now there's no more nonsense , Let's see how the order function is implemented . ...

  5. javascript Get address bar parameters / value

    //URL: http://www.example.com/?var1=val1&var2=val2=val3&test=3&test=43&aaa=#2 //wind ...

  6. tab Switch *****

    <!doctype html><html lang="en"><head> <meta charset="UTF-8" ...

  7. python And __call__()

    __call__ stay Python in , A function is actually an object : >>> f = abs >>> f.__name__ 'abs' >>> f(-123) ...

  8. Try to understand cookie and session

    web One of the characteristics of service is to provide personalized service , Serving many clients , So each user is different , The service is naturally different , So remember the users and their status , This is also the common function of many applications . because http It's stateless ,Session and Cookie It's two ...

  9. JUC Gather them together JUC Set class in

    Java Collection package stay "Java Collection Series 01 And General framework " in , Introduce java The architecture of the collection . The main contents include Collection The collection and Map class : and Collection The set can be divided into List( ...

  10. instanceof Usage and essence :

    import static java.lang.System.*; public class InstanceofTest{ public static void main(String[] args ...