Interview questions _ questions about Java generics

Source: Internet
Author: User

1. What are generics in Java? What are the benefits of using generics?

This is one of the questions you'll be asked about in a variety of Java generic interviews, focusing primarily on beginner and mid-level interviews. Those with a Java1.4 or earlier development background know how inconvenient it is to store objects in a collection and type-convert them before they are used. Generics prevent that situation from happening. It provides type safety at compile time, ensuring that you can only put objects of the correct type into the collection, avoiding classcastexception at run time.

2. How does the Java generics work? What is type erase?

This is a better question for a generic face. Generics are implemented by type Erasure, and the compiler erases all type-related information at compile time, so there is no type-related information at run time. For example, list<string> is represented only by a List at run time. The purpose of this is to make sure that the Binary class library is compatible with the version developed prior to Java 5. You cannot access the type parameter at run time because the compiler has converted the generic type to the original type. Depending on your answer to this generic question, you'll get some follow-up questions, such as why generics are implemented by type Erasure or show you some of the wrong generic code that causes the compiler to make an error. Please read how generics in my Java work to learn more.

3. What are qualified wildcard and unqualified wildcard characters in generics?

This is another very popular Java generic surface question. Restrictions on the type are limited by wildcard characters. There are two kinds of qualified wildcard characters, one is < Extends t> it sets the upper bounds of the type by ensuring that the type must be a subclass of T, and the other is < Super t> It sets the lower bound of a type by ensuring that the type must be the parent of T. A generic type must be initialized with a qualified type, or it will result in a compilation error. On the other hand, <?> represents an unqualified wildcard, because <?> can be substituted for any type. For more information, see the differences between qualifying wildcards and unqualified wildcards in my article generics.

4. list<? Extends t> and list <? What is the difference between Super t>?

This is related to the previous interview question, and sometimes the interviewer will use it to evaluate your understanding of generics, rather than asking you directly what qualifies wildcards and unqualified wildcards. These two List declarations are all examples of qualifying wildcard characters, LIST< Extends t> can accept any list of types that inherit from T, and list<? Super T> can accept a list of any of the parent classes of T. e.g. list<? Extends number> can accept list<integer> or list<float>. More information can be found in the connection that appears in this section.

5. How do I write a generic method that can accept generic parameters and return generic types?

Writing a generic method is not difficult, you need to replace the original type with a generic type, such as using a widely recognized type placeholder such as T, E or K,V. For an example of a generic method, see the Java Collection Class framework. In the simplest case, a generic method might look like this:

Public V put (K key, V value) {

Return Cache.put (key, value);

}

6. How do I use generics to write classes with parameters in Java?

This is an extension of the last interview question. The interviewer may ask you to write a type-safe class with generics, rather than writing a generic method. The key is still to use generic types instead of the original types, and to use the standard placeholders that are used in the JDK.

7. Write a generic program to implement LRU caching?

This is the equivalent of an exercise for people who like Java programming. To give you a hint, linkedhashmap can be used to implement a fixed-size LRU cache, which moves the oldest key-value pairs out of the cache when the LRU cache is full. Linkedhashmap provides a method called Removeeldestentry (), which is used by the put () and Putall () calls to delete the oldest key-value pairs. Of course, if you've already written a junit test that you can run, you can write your own implementation code at your own discretion.

8. Can you pass the list<string> to a method that accepts list<object> parameters?

For anyone unfamiliar with generics, this Java generic topic looks confusing because at first glance the String is an Object, so list<string> should be used where it needs to be list<object>, But that is not the case. If you do this, you will cause a compilation error. If you take this one step further, you will find that Java does this to make sense, because list<object> can store objects of any type, including String, Integer, and so on, while list<string> can only be used to store strings.

List<object> objectList;

List<string> stringlist;

ObjectList = stringlist; Compilation error incompatible types

9. Can I use generics in array?

This is probably the simplest of the Java generic interview questions, but if you want to know that the array does not actually support generics, that's why Joshua Bloch suggests using list instead of array in the effective Java book. Because list can provide a type-safety guarantee for the compile period, array does not.

10. How do I block a warning from a type that is not checked in Java?

If you mix generics with primitive types, such as the following code, Java 5 's Javac compiler produces warnings that are not checked by the type, such as

list<string> rawlist = new ArrayList ()

Note: Hello.java uses an operation that is not checked or is called unsafe;

This warning can be masked using @suppresswarnings ("unchecked") annotations.

Java generic surface question supplement update:

I've got a couple of Java generics. Questions to share with you, these questions focus on the difference between a generic type and a primitive type, and whether we can use object instead of qualifying wildcard usage, and so on:

What is the difference between the list<object> and the original type list in Java?

The main difference between the original type and the parameter type <Object> is that at compile time the compiler does not type safety checks on the original type, but the type with the parameter is checked, and by using object as the type, you can tell the compiler that the method can accept objects of any type. such as String or integer. The point of this problem is the correct understanding of the primitive types in generics. The 2nd difference between them is that you can pass any type with a parameter to the original type List, but you cannot pass list<string> to the method that accepts List<object>, because a compilation error occurs. For more details, see how generics work in Java.

What is the difference between list<?> and list<object> in Java?

This question looks very much like the previous question, but it is fundamentally different. List<?> is an unknown type of list, and list<object> is actually any type of list. You can put List<string>, list<integer> assigned to List<?>, but not list<string> assigned to list<object>.

List<?> Listofanytype;

list<object> listofobject = new arraylist<object> ();

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

list<integer> Listofinteger = new arraylist<integer> ();

Listofanytype = listofstring; Legal

Listofanytype = Listofinteger; Legal

Listofobjecttype = (list<object>) listofstring; Compiler error–in-convertible Types

For more information on wildcards see the generic wildcard example in Java

The difference between the list<string> and the original type list.

The question is similar to "what is the difference between a primitive type and a parameter type". With parameter types is type-safe, and its type safety is guaranteed by the compiler, but the original type list is not type-safe. You cannot put any other type of object other than string into a list of type string, and you can save any type of object in the original list. With a generic parameter type you do not need to do a type conversion, but for the original type you need an explicit type conversion.

List listofrawtypes = new ArrayList ();

Listofrawtypes.add ("abc");

Listofrawtypes.add (123); The compiler allows this – the runtime will have an exception

String item = (string) listofrawtypes.get (0); An explicit type conversion is required

Item = (String) listofrawtypes.get (1); Throw classcastexception, because integer cannot be converted to string

list<string> listofstring = new ArrayList ();

Listofstring.add ("ABCD");

Listofstring.add (1234); Compile errors, better than throwing exceptions at run time

item = listofstring.get (0); No explicit type conversions are required – compiler auto-conversion

These are frequently-occurring questions and Answers in a Java generic interview. All of these interview questions are not difficult, in fact they are based on generic basic knowledge. Any Java programmer with a good understanding of generics is sure to be familiar with these generic topics. If you have any good face questions, no matter what interview you encounter, or if you want to know the answers to any Java generic interview questions.

original address: Http://www.oschina.net/translate/10-interview-questions-on-java-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.