Home >Java >JavaInterview questions >Summary of 2020 new Java basic interview questions
The difference between ==, equals and hashCode in java
(More interview question recommendations: java interview questions and answers)
Data types in Java can be divided into two categories:
Basic data types, also called primitive data types To compare byte, short, char, int, long, float, double, boolean, use the double equal sign (==), and compare their values.
Reference type (class, interface, array) When they compare using (==), they compare their storage addresses in memory. Therefore, unless they are the same new object, the result of their comparison is true, otherwise the result of the comparison is false. Objects are placed on the heap, and the reference (address) of the object is stored on the stack. First look at the virtual machine memory map and code:
public class testDay { public static void main(String[] args) { String s1 = new String("11"); String s2 = new String("11"); System.out.println(s1 == s2); System.out.println(s1.equals(s2)); } }
The result is:
false
true
Both s1 and s2 store the addresses of the corresponding objects. Therefore, if s1== s2 is used, the address values of the two objects are compared (that is, whether the references are the same), which is false. When calling the equals direction, the value in the corresponding address is compared, so the value is true. Here we need to describe equals() in detail.
The equals() method is used to determine whether other objects are equal to this object. It is defined in Object, so any object has the equals() method. The difference is whether the method is overridden or not.
Let’s take a look at the source code first:
public boolean equals(Object obj) { return (this == obj); }
Obviously, Object defines a comparison of the address values of two objects (that is, comparing whether the references are the same). But why does calling equals() in String compare not the address but the value in the heap memory address? Here is the key point. When encapsulation classes such as String, Math, Integer, Double, etc. use the equals() method, they have already covered the equals() method of the object class. Take a look at the rewritten equals() in String:
public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = value.length; if (n == anotherString.value.length) { char v1[] = value; char v2[] = anotherString.value; int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) return false; i++; } return true; } } return false; }
After rewriting, this is the content comparison, and it is no longer the comparison of the previous address. By analogy, classes such as Math, Integer, Double, etc. all override the equals() method to compare contents. Of course, basic types perform value comparisons.
It should be noted that when the equals() method is overridden, hashCode() will also be overridden. According to the implementation of the general hashCode() method, equal objects must have equal hashcodes. Why is this so? Here we briefly mention hashcode.
It is obviously a question about the difference between ==, equals and hashCode in Java, but why is it suddenly related to hashcode(). You must be very depressed, okay, let me give a simple example and you will know why hashCode is involved when == or equals.
For example: If you want to find out whether a collection contains an object, how should you write the program? If you don't use the indexOf method, just traverse the collection and compare whether you think of it. What if there are 10,000 elements in the collection, it would be tiring, right? So in order to improve efficiency, the hash algorithm was born. The core idea is to divide the collection into several storage areas (can be seen as buckets). Each object can calculate a hash code and can be grouped according to the hash code. Each group corresponds to a certain storage area. In this way, an object can be grouped according to the hash code. Its hash code can be divided into different storage areas (different areas).
So when comparing elements, the hashcode is actually compared first, and if they are equal, the equal method is compared.
Look at the hashcode diagram:
#An object generally has a key and a value, and its hashCode value can be calculated based on the key. Then it is stored in different storage areas according to its hashCode value, as shown in the figure above. Multiple values can be stored in different areas because hash conflicts are involved. Simple: If the hashCode of two different objects is the same, this phenomenon is called a hash conflict. Simply put, it means the hashCode is the same but equals is a different value. For comparing 10,000 elements, there is no need to traverse the entire collection. You only need to calculate the hashCode of the key of the object you want to find, and then find the storage area corresponding to the hashCode. The search is over.
大概可以知道,先通过hashcode来比较,如果hashcode相等,那么就用equals方法来比较两个对象是否相等。再重写了equals最好把hashCode也重写。其实这是一条规范,如果不这样做程序也可以执行,只不过会隐藏bug。一般一个类的对象如果会存储在HashTable,HashSet,HashMap等散列存储结构中,那么重写equals后最好也重写hashCode。
总结:
byte 是 字节
bit 是 位
1 byte = 8 bit
char在java中是2个字节,java采用unicode,2个字节来表示一个字符
short 2个字节
int 4个字节
long 8个字节
float 4个字节
double 8个字节
延伸: 关于Integer和int的比较
Integer i = new Integer(100); Integer j = new Integer(100); System.out.print(i == j); //false
Integer i = new Integer(100); int j = 100; System.out.print(i == j); //true
Integer i = new Integer(100); Integer j = 100; System.out.print(i == j); //false
Integer i = 100; Integer j = 100; System.out.print(i == j); //true
Integer i = 128; Integer j = 128; System.out.print(i == j); //false
对于第4条的原因: java在编译Integer i = 100 ;时,会翻译成为Integer i = Integer.valueOf(100);,而java API中对Integer类型的valueOf的定义如下:
public static Integer valueOf(int i){ assert IntegerCache.high >= 127; if (i >= IntegerCache.low && i <p>java对于-128到127之间的数,会进行缓存,Integer i = 127时,会将127进行缓存,下次再写Integer j = 127时,就会直接从缓存中取,就不会new了</p><h2 class="heading" data-id="heading-6">4. java多态的理解</h2><h3 class="heading" data-id="heading-7">1.多态概述</h3><ol> <li><p>多态是继封装、继承之后,面向对象的第三大特性。</p></li> <li><p>多态现实意义理解:</p></li> </ol>
现实事物经常会体现出多种形态,如学生,学生是人的一种,则一个具体的同学张三既是学生也是人,即出现两种形态。
Java作为面向对象的语言,同样可以描述一个事物的多种形态。如Student类继承了Person类,一个Student的对象便既是Student,又是Person。
多态体现为父类引用变量可以指向子类对象。
前提条件:必须有子父类关系。
注意:在使用多态后的父类引用变量调用方法时,会调用子类重写后的方法。
定义格式:父类类型 变量名=new 子类类型();
Fu f=new Zi();
System.out.println(f.num);//f是Fu中的值,只能取到父中的值
Fu f1=new Zi();
System.out.println(f1.show());//f1的门面类型是Fu,但实际类型是Zi,所以调用的是重写后的方法。
作用:用来判断某个对象是否属于某种数据类型。
* 注意: 返回类型为布尔类型
使用案例:
Fu f1=new Zi(); Fu f2=new Son();if(f1 instanceof Zi){ System.out.println("f1是Zi的类型"); }else{ System.out.println("f1是Son的类型"); }
多态的转型分为向上转型和向下转型两种
向上转型:多态本身就是向上转型过的过程
使用格式:父类类型 变量名=new 子类类型();
适用场景:当不需要面对子类类型时,通过提高扩展性,或者使用父类的功能就能完成相应的操作。
向下转型:一个已经向上转型的子类对象可以使用强制类型转换的格式,将父类引用类型转为子类引用各类型
使用格式:子类类型 变量名=(子类类型)父类类型的变量;
适用场景:当要使用子类特有功能时。
例1:
package day0524; public class demo04 { public static void main(String[] args) { People p=new Stu(); p.eat(); //调用特有的方法 Stu s=(Stu)p; s.study(); //((Stu) p).study(); } } class People{ public void eat(){ System.out.println("吃饭"); } } class Stu extends People{ @Override public void eat(){ System.out.println("吃水煮肉片"); } public void study(){ System.out.println("好好学习"); } } class Teachers extends People{ @Override public void eat(){ System.out.println("吃樱桃"); } public void teach(){ System.out.println("认真授课"); } }
答案:吃水煮肉片 好好学习
例2:
请问题目运行结果是什么?
package day0524; public class demo1 { public static void main(String[] args) { A a=new A(); a.show(); B b=new B(); b.show(); } } class A{ public void show(){ show2(); } public void show2(){ System.out.println("A"); } } class B extends A{ public void show2(){ System.out.println("B"); } } class C extends B{ public void show(){ super.show(); } public void show2(){ System.out.println("C"); } }
答案:A B
StringBuffer和StringBuilder区别
将一个类定义在另一个类里面或者一个方法里面,这样的类称为内部类。
成员内部类 成员内部类可以无条件访问外部类的所有成员属性和成员方法(包括private成员和静态成员)。 当成员内部类拥有和外部类同名的成员变量或者方法时,会发生隐藏现象,即默认情况下访问的是成员内部类的成员。
局部内部类 局部内部类是定义在一个方法或者一个作用域里面的类,它和成员内部类的区别在于局部内部类的访问仅限于方法内或者该作用域内。
匿名内部类 匿名内部类就是没有名字的内部类
静态内部类 指被声明为static的内部类,他可以不依赖内部类而实例,而通常的内部类需要实例化外部类,从而实例化。静态内部类不可以有与外部类有相同的类名。不能访问外部类的普通成员变量,但是可以访问静态成员变量和静态方法(包括私有类型) 一个 静态内部类去掉static 就是成员内部类,他可以自由的引用外部类的属性和方法,无论是静态还是非静态。但是不可以有静态属性和方法
(学习视频推荐:java课程)
Abstract class: If a class contains abstract methods, the class should be declared as an abstract class using the abstract keyword.
Meaning:
In a word, when both a unified interface and instance variables or default methods are needed , you can use it. The most common ones are:
The answer is: Yes
There can be no abstract methods in abstract classes, but those with abstract methods must be abstract classes. Therefore, there can be no abstract methods in abstract classes in Java. Note that even abstract classes without abstract methods and properties cannot be instantiated.
在平时看源码的时候我们经常看到泛型,且经常会看到extends和super的使用,看过其他的文章里也有讲到上界通配符和下届通配符,总感觉讲的不够明白。这里备注一下,以免忘记。
这两点不难理解,extends修饰的只能取,不能放,这是为什么呢? 先看一个列子:
public class Food {} public class Fruit extends Food {} public class Apple extends Fruit {} public class Banana extends Fruit{} public class GenericTest { public void testExtends(List extends Fruit> list){ //报错,extends为上界通配符,只能取值,不能放. //因为Fruit的子类不只有Apple还有Banana,这里不能确定具体的泛型到底是Apple还是Banana,所以放入任何一种类型都会报错 //list.add(new Apple()); //可以正常获取 Fruit fruit = list.get(1); } public void testSuper(List super Fruit> list){ //super为下界通配符,可以存放元素,但是也只能存放当前类或者子类的实例,以当前的例子来讲, //无法确定Fruit的父类是否只有Food一个(Object是超级父类) //因此放入Food的实例编译不通过 list.add(new Apple()); // list.add(new Food()); Object object = list.get(1); } }
在testExtends方法中,因为泛型中用的是extends,在向list中存放元素的时候,我们并不能确定List中的元素的具体类型,即可能是Apple也可能是Banana。因此调用add方法时,不论传入new Apple()还是new Banana(),都会出现编译错误。
理解了extends之后,再看super就很容易理解了,即我们不能确定testSuper方法的参数中的泛型是Fruit的哪个父类,因此在调用get方法时只能返回Object类型。结合extends可见,在获取泛型元素时,使用extends获取到的是泛型中的上边界的类型(本例子中为Fruit),范围更小。
总结:在使用泛型时,存取元素时用super,获取元素时,用extends。
不能,父类的静态方法能够被子类继承,但是不能够被子类重写,即使子类中的静态方法与父类中的静态方法完全一样,也是两个完全不同的方法。
class Fruit{ static String color = "五颜六色"; static public void call() { System.out.println("这是一个水果"); } } public class Banana extends Fruit{ static String color = "黄色"; static public void call() { System.out.println("这是一个香蕉"); } public static void main(String[] args) { Fruit fruit = new Banana(); System.out.println(fruit.color); //五颜六色 fruit.call(); //这是一个水果 } }
如代码所示,如果能够被重写,则输出的应该是这是一个香蕉。与此类似的是,静态变量也不能够被重写。如果想要调用父类的静态方法,应该使用类来调用。 那为什么会出现这种情况呢? 我们要从重写的定义来说:
重写指的是根据运行时对象的类型来决定调用哪个方法,而不是根据编译时的类型。
对于静态方法和静态变量来说,虽然在上述代码中使用对象来进行调用,但是底层上还是使用父类来调用的,静态变量和静态方法在编译的时候就将其与类绑定在一起。既然它们在编译的时候就决定了调用的方法、变量,那就和重写没有关系了。
静态属性和静态方法是否可以被继承
可以被继承,如果子类中有相同的静态方法和静态变量,那么父类的方法以及变量就会被覆盖。要想调用就就必须使用父类来调用。
class Fruit{ static String color = "五颜六色"; static String xingzhuang = "奇形怪状"; static public void call() { System.out.println("这是一个水果"); } static public void test() { System.out.println("这是没有被子类覆盖的方法"); } } public class Banana extends Fruit{ static String color = "黄色"; static public void call() { System.out.println("这是一个香蕉"); } public static void main(String[] args) { Banana banana = new Banana(); banana.test(); //这是没有被子类覆盖的方法 banana.call(); //调用Banana类中的call方法 这是一个香蕉 Fruit.call(); //调用Fruit类中的方法 这是一个水果 System.out.println(banana.xingzhuang + " " + banana.color); //奇形怪状 黄色 } }
从上述代码可以看出,子类中覆盖了父类的静态方法的话,调用的是子类的方法,这个时候要是还想调用父类的静态方法,应该是用父类直接调用。如果子类没有覆盖,则调用的是父类的方法。静态变量与此相似。
You can read this article: juejin.im/post/684490…
If Intent in Android wants to transfer class objects, it can be achieved in two ways.
Method 1: Serializable, the class to be passed implements the Serializable interface to pass the object, Method 2: Parcelable, the class to be transferred implements the Parcelable interface to transfer the object.
Serializable (comes with Java): Serializable means serialization, which means converting an object into a storable or transmittable state. Serialized objects can be transmitted over the network or stored locally. Serializable is a tagged interface, which means that Java can efficiently serialize this object without implementing methods.
Parcelable (Android-specific): The original design intention of Android's Parcelable is because Serializable is too slow (using reflection), in order to facilitate communication between different components in the program and between different Android programs (AIDL) Designed to efficiently transfer data that only exists in memory. The implementation principle of the Parcelable method is to decompose a complete object, and each part after decomposition is a data type supported by Intent, thus realizing the function of passing the object.
Efficiency and selection:
The performance of Parcelable is better than that of Serializable, because the latter frequently GCs during the reflection process, so it is recommended to use Parcelable when transferring data between memories, such as transferring data between activities. Serializable can persist data for easy storage, so choose Serializable when you need to save or transmit data over the network. Because Parcelable may be different in different versions of Android, it is not recommended to use Parcelable for data persistence. Parcelable cannot be used when data is to be stored on disk, because Parcelable cannot guarantee the persistence of data when the outside world changes. Although Serializable is less efficient, it is still recommended to use Serializable at this time.
When passing complex data types through intent, one of the two interfaces must be implemented first. The corresponding methods are getSerializableExtra() and getParcelableExtra().
The static properties and methods of the parent class can be inherited by the subclass
cannot be overridden by the subclass : When the reference of the parent class points to the subclass When using an object to call a static method or static variable, the method or variable in the parent class is called. It is not overridden by subclasses.
Reason:
Because the static method has allocated memory since the program started running, which means it has been hard-coded. All objects that reference this method (either objects of the parent class or objects of the subclass) point to the same piece of data in memory, which is the static method.
If a static method with the same name is defined in a subclass, it will not be overridden. Instead, another static method in the memory should be allocated to the subclass, and there is no such thing as rewriting.
Inner classes are classes defined inside a class. Why are there inner classes?
We know that in Java, classes are single inheritance, and a class can only inherit another concrete class or abstract class (which can implement multiple interfaces). The purpose of this design is that in multiple inheritance, when there are duplicate attributes or methods in multiple parent classes, the call results of the subclass will be ambiguous, so single inheritance is used.
The reason for using inner classes is that each inner class can independently inherit an (interface) implementation, so whether the outer class has inherited an (interface) implementation, it has no effect on the inner class.
In our programming, sometimes there are some problems that are difficult to solve using interfaces. At this time, we can use the ability provided by internal classes to inherit multiple concrete or abstract classes to solve these programs. Design issues. It can be said that interfaces only solve part of the problem, and inner classes make the solution of multiple inheritance more complete.
Before talking about static inner classes, first understand the member inner classes (non-static inner classes).
Member inner class
Member inner class is also the most common inner class. It is a member of the outer class, so it can have unlimited access to all the outer classes. Although the member attributes and methods are private, if the outer class wants to access the member attributes and methods of the inner class, it needs to access it through the inner class instance.
Two points should be noted in the member inner class:
There cannot be any static variables and methods in the member inner class;
The member inner class is attached to the outer class, so the inner class can only be created after the outer class is created first.
Static inner class
There is one biggest difference between static inner classes and non-static inner classes: non-static inner classes are compiled after they are compiled A reference is then implicitly held to the outside world in which it was created, but the static inner class does not.
The absence of this reference means:
Its creation does not need to depend on the peripheral class.
It cannot use non-static member variables and methods of any peripheral class.
The other two internal classes: local internal classes and anonymous internal classes
Local internal classes
Local internal classes are Nested within methods and scopes, the use of this class is mainly to apply and solve more complex problems. We want to create a class to assist our solutions, but by then we do not want this class to be publicly available, so we A local inner class is generated. The local inner class is compiled like the member inner class, but its scope changes. It can only be used in this method and attribute, and it will become invalid when the method and attribute are removed.
Anonymous inner classes
Anonymous inner classes have no access modifiers.
new Anonymous inner class, this class must exist first.
When the formal parameter of the method needs to be used by the anonymous inner class, then the formal parameter must be final.
Anonymous inner classes have no explicit constructor, and the compiler will automatically generate a constructor that references the outer class.
Related recommendations:Getting started with java
The above is the detailed content of Summary of 2020 new Java basic interview questions. For more information, please follow other related articles on the PHP Chinese website!