Java basic interview questions - generics
Sep 28, 2020 pm 04:26 PM139. What are generics in Java? What are the benefits of using generics?
(Recommended more related interview questions: java interview questions And answer )
Generics are a new feature of Java SE 1.5. The essence of generics is a parameterized type, which means that the data type being operated is specified as a parameter.
Benefits:
1. Type safety, providing type detection during compilation
2. Back and forth compatibility
3. Generalized code, the code can be updated More reuse
4. High performance. Code written in GJ (generic JAVA) can bring more type information to the Java compiler and virtual machine. This information can further optimize the Java program. provide conditions.
140, How do Java generics work? What is type erasure? How does it work?
1. Type checking: Provide type checking before generating bytecode
2. Type erasure: All type parameters are replaced with their qualified types, including classes, variables and methods ( Type erasure)
3. If type erasure conflicts with polymorphism, generate a bridge method in the subclass to solve the problem
4. If the return type of a generic method is called is erased, a cast is inserted when the method is called
Type erasure:
All type parameters are replaced with their qualified types:
For example
T->Object ? extends BaseClass->BaseClass
How it works:
Generics are implemented through type erasure. The compiler erases all type-related information at compile time, so there is no type-related information at runtime. . For example, List
141, can you pass List
For anyone who is not familiar with generics, this Java generics question may seem confusing, because at first glance String is a kind of Object, so List
List<Object> objectList; List<String> stringList; objectList = stringList; //compilation error incompatible types
142, How to prevent unchecked type warnings in Java?
If you mix generics and primitive types, such as the following code, the javac compiler of java 5 will generate Type unchecked warnings, such as
List<String> rawList = newArrayList()
Note: Hello.java uses unchecked or unsafe operations;
This kind of warning can be annotated with @SuppressWarnings("unchecked") to shield.
143, What is the difference between List
The main difference between primitive type and parameterized type
The test point of this question lies in the correct understanding of primitive types in generics. The second difference between them is that you can pass any type with parameters to the primitive type List, but you cannot pass List
144, write a generic program to implement LRU cache?
This is equivalent to an exercise for people who like Java programming. To give you a hint, LinkedHashMap can be used to implement a fixed-size LRU cache. When the LRU cache is full, it will move the oldest key-value pair out of the cache.
LinkedHashMap provides a method called removeEldestEntry(), which will be called by put() and putAll() to delete the oldest key-value pair. Of course, if you've already written a running JUnit test, you're free to write your own implementation code.
(Recommended tutorial: java course)
145, can generics be used in Array?
This may be Java generics This is the simplest interview question. Of course, the premise is that you know that Array does not actually support generics. This is why Joshua Bloch recommends using List instead of Array in the book Effective Java, because List can provide compile-time types. Security is guaranteed, while Array cannot.
146, How to write a generic method so that it can accept generic parameters and return a generic type?
編寫泛型方法并不困難,你需要用泛型類型來替代原始類型,比如使用T, E or K,V等被廣泛認可的類型占位符。最簡單的情況下,一個泛型方法可能會像這樣:
public V put(K key, V value) { return cahe.put(key,value); }
147,C++模板和java泛型之間有何不同?
java泛型實現(xiàn)根植于“類型消除”這一概念。當(dāng)源代碼被轉(zhuǎn)換為Java虛擬機字節(jié)碼時,這種技術(shù)會消除參數(shù)化類型。有了Java泛型,我們可以做的事情也并沒有真正改變多少;他只是讓代碼變得漂亮些。鑒于此,Java泛型有時也被稱為“語法糖”。
這和 C++模板截然不同。在 C++中,模板本質(zhì)上就是一套宏指令集,只是換了個名頭,編譯器會針對每種類型創(chuàng)建一份模板代碼的副本。
由于架構(gòu)設(shè)計上的差異,Java泛型和C++模板有很多不同點:
C++模板可以使用int等基本數(shù)據(jù)類型。Java則不行,必須轉(zhuǎn)而使用Integer。
在Java中,可以將模板的參數(shù)類型限定為某種特定類型。
在C++中,類型參數(shù)可以實例化,但java不支持。
在Java中,類型參數(shù)不能用于靜態(tài)方法(?)和變量,因為它們會被不同類型參數(shù)指定的實例共享。在C++,這些類時不同的,因此類型參數(shù)可以用于靜態(tài)方法和靜態(tài)變量。
在Java中,不管類型參數(shù)是什么,所有的實例變量都是同一類型。類型參數(shù)會在運行時被抹去。在C++中,類型參數(shù)不同,實例變量也不同。
相關(guān)推薦:java入門
The above is the detailed content of Java basic interview questions - generics. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

There are three common methods to traverse Map in Java: 1. Use entrySet to obtain keys and values at the same time, which is suitable for most scenarios; 2. Use keySet or values to traverse keys or values respectively; 3. Use Java8's forEach to simplify the code structure. entrySet returns a Set set containing all key-value pairs, and each loop gets the Map.Entry object, suitable for frequent access to keys and values; if only keys or values are required, you can call keySet() or values() respectively, or you can get the value through map.get(key) when traversing the keys; Java 8 can use forEach((key,value)->

Optional can clearly express intentions and reduce code noise for null judgments. 1. Optional.ofNullable is a common way to deal with null objects. For example, when taking values ??from maps, orElse can be used to provide default values, so that the logic is clearer and concise; 2. Use chain calls maps to achieve nested values ??to safely avoid NPE, and automatically terminate if any link is null and return the default value; 3. Filter can be used for conditional filtering, and subsequent operations will continue to be performed only if the conditions are met, otherwise it will jump directly to orElse, which is suitable for lightweight business judgment; 4. It is not recommended to overuse Optional, such as basic types or simple logic, which will increase complexity, and some scenarios will directly return to nu.

The core workaround for encountering java.io.NotSerializableException is to ensure that all classes that need to be serialized implement the Serializable interface and check the serialization support of nested objects. 1. Add implementsSerializable to the main class; 2. Ensure that the corresponding classes of custom fields in the class also implement Serializable; 3. Use transient to mark fields that do not need to be serialized; 4. Check the non-serialized types in collections or nested objects; 5. Check which class does not implement the interface; 6. Consider replacement design for classes that cannot be modified, such as saving key data or using serializable intermediate structures; 7. Consider modifying

In Java, Comparable is used to define default sorting rules internally, and Comparator is used to define multiple sorting logic externally. 1.Comparable is an interface implemented by the class itself. It defines the natural order by rewriting the compareTo() method. It is suitable for classes with fixed and most commonly used sorting methods, such as String or Integer. 2. Comparator is an externally defined functional interface, implemented through the compare() method, suitable for situations where multiple sorting methods are required for the same class, the class source code cannot be modified, or the sorting logic is often changed. The difference between the two is that Comparable can only define a sorting logic and needs to modify the class itself, while Compar

Method reference is a way to simplify the writing of Lambda expressions in Java, making the code more concise. It is not a new syntax, but a shortcut to Lambda expressions introduced by Java 8, suitable for the context of functional interfaces. The core is to use existing methods directly as implementations of functional interfaces. For example, System.out::println is equivalent to s->System.out.println(s). There are four main forms of method reference: 1. Static method reference (ClassName::staticMethodName); 2. Instance method reference (binding to a specific object, instance::methodName); 3.

To deal with character encoding problems in Java, the key is to clearly specify the encoding used at each step. 1. Always specify encoding when reading and writing text, use InputStreamReader and OutputStreamWriter and pass in an explicit character set to avoid relying on system default encoding. 2. Make sure both ends are consistent when processing strings on the network boundary, set the correct Content-Type header and explicitly specify the encoding with the library. 3. Use String.getBytes() and newString(byte[]) with caution, and always manually specify StandardCharsets.UTF_8 to avoid data corruption caused by platform differences. In short, by

There are three common ways to parse JSON in Java: use Jackson, Gson, or org.json. 1. Jackson is suitable for most projects, with good performance and comprehensive functions, and supports conversion and annotation mapping between objects and JSON strings; 2. Gson is more suitable for Android projects or lightweight needs, and is simple to use but slightly inferior in handling complex structures and high-performance scenarios; 3.org.json is suitable for simple tasks or small scripts, and is not recommended for large projects because of its lack of flexibility and type safety. The choice should be decided based on actual needs.

How to quickly create new emails in Outlook is as follows: 1. The desktop version uses the shortcut key Ctrl Shift M to directly pop up a new email window; 2. The web version can create new emails in one-click by creating a bookmark containing JavaScript (such as javascript:document.querySelector("divrole='button'").click()); 3. Use browser plug-ins (such as Vimium, CrxMouseGestures) to trigger the "New Mail" button; 4. Windows users can also select "New Mail" by right-clicking the Outlook icon of the taskbar
