Why use generics and iterators

Why use generics and iterators + interview questions

Generics

1) Why use generics?

Before generics is not born, we often encounter such a problem, as shown in the following code:

ArrayList arrayList = new ArrayList();
arrayList.add("Java");
arrayList.add(24);
for (int i = 0; i < arrayList.size(); i++) {
    String str = (String) arrayList.get(i);
    System.out.println(str);
}

Looks like no big problem, but also the normal compiler, but really up and running it will error:

Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String

at xxx(xxx.java:12)

Type conversion error, when we give ArrayList into different types of data, but one type of reception, many similar error occurs, it may be more often, because the developers careless caused. That there is no good way to prevent such problems? This time Java language provides a good solution - "generic."

2) introduction of generics

Generics : parameterized type is to solve the problem of uncertain type generic in nature.
The use of generics, please refer to the following code:

ArrayList<String> arrayList = new ArrayList();
arrayList.add("Java");

This time If you add non-String types of elements to arrayList, the compiler will report an error, to remind developers to insert the same type of element.

This can be avoided at the beginning of example, the type of inconsistency cause problems during program execution error of the.

Advantage 3) generics

The main advantage of generics in the following three aspects.

  • Security: do not worry about the wrong type conversion program is running appears.
  • Type conversion avoided: if non-generic, acquired elements are of type Object, need cast.
  • High readability: coding stage clearly know the type of elements in the collection.

Iterator (Iterator)

1) Why use iterators?

Recall that before the iterator (Iterator) does not appear, if you want to traverse the arrays and collections, need to use.

Array traversal, as follows:

String[] arr = new String[]{"Java", "Java虚拟机", "Java中文社群"};
for (int i = 0; i < arr.length; i++) {
    String item = arr[i];
}

Traverse the set, as follows:

List<String> list = new ArrayList<String>() {{
    add("Java");
    add("Java虚拟机");
    add("Java中文社群");
}};
for (int i = 0; i < list.size(); i++) {
    String item = list.get(i);
}

It produced iterator is traversing different types of containers, provides a standard unified approach.

Iterates over, as follows:

Iterator iterator = list.iterator();
while (iterator.hasNext()) {
    Object object = iterator.next();
    // do something
}

Summary : Use the iterator can not focus on the internal details of the container, traverse different types of containers in the same way.

2) Introduction iterator

Iterator objects are used to traverse all the elements within the container, it is also a common design pattern.

Iterator contains the following four methods.

  • hasNext (): boolean - whether there are elements that can be accessed within the container.
  • next (): E - Returns the next element.
  • remove (): void - delete the current element.
  • forEachRemaining (Consumer): void - JDK 8 added, a lambda expression traverse the container elements.

Iterator used as follows:

List<String> list = new ArrayList<String>() {{
    add("Java");
    add("Java虚拟机");
    add("Java中文社群");
}};
Iterator iterator =  list.iterator();
// 遍历
while (iterator.hasNext()){
    String str = (String) iterator.next();
    if (str.equals("Java中文社群")){
        iterator.remove();
    }
}
System.out.println(list);

Program execution results:

[Java, Java虚拟机]

forEachRemaining used as follows:

List<String> list = new ArrayList<String>() {{
    add("Java");
    add("Java虚拟机");
    add("Java中文社群");
}};
// forEachRemaining 使用
list.iterator().forEachRemaining(item -> System.out.println(item));

Related interview questions

1. Why iterator's next () returns the type Object?

A: Because the iterator does not require the internal details of the container, so the next () returns the type Object can receive any type of object.

2.HashMap traversal methods have several?

A: HashMap traversal divided into the following four ways.

  • Method 1: entrySet traversal
  • Second way: iterator traversal
  • Three ways: through all the key and value
  • Four ways: by traversing key value

The codes in the above manner to achieve the following:

Map<String, String> hashMap = new HashMap();
hashMap.put("name", "老王");
hashMap.put("sex", "你猜");
// 方式一:entrySet 遍历
for (Map.Entry item : hashMap.entrySet()) {
  System.out.println(item.getKey() + ":" + item.getValue());
}
// 方式二:iterator 遍历
Iterator<Map.Entry<String, String>> iterator = hashMap.entrySet().iterator();
while (iterator.hasNext()) {
  Map.Entry<String, String> entry = iterator.next();
  System.out.println(entry.getKey() + ":" + entry.getValue());
}
// 方式三:遍历所有的 key 和 value
for (Object k : hashMap.keySet()) {
  // 循环所有的 key
  System.out.println(k);
}
for (Object v : hashMap.values()) {
  // 循环所有的值
  System.out.println(v);
}
// 方式四:通过 key 值遍历
for (Object k : hashMap.keySet()) {
  System.out.println(k + ":" + hashMap.get(k));
}

3. The following generic statement about the error is?

A: generic class can be modified
B: generic methods can be modified
C: not modified Generic Interface
D: the above statement is all wrong

A: The election C, can be modified generic classes, methods, interfaces, variables.
E.g:

public interface Iterable\<T\> {
}

4. What is the result of the following program execution is?

List<String> list = new ArrayList<>();
List<Integer> list2 = new ArrayList<>();
System.out.println(list.getClass() == list2.getClass());

A: Results of the implementation is true.
Topic resolve: Java generics at compile-time type will be erased, so List<String> listand List<Integer> list2the result of type erasure are java.util.ArrayLis, then the result list.getClass () == list2.getClass () must also be true.

5. List<Object>and List<?>what is the difference?

A: List<?>can accommodate any type, but List<?>after being assigned, is not allowed to add and modify operated; and List<Object>and List<?>except that after the assignment it can add and modify operations, as shown below:

6. can be List<String>assigned to List<Object>it?

A: No, the compiler will complain, as shown below:

List and List<Object>what the difference is?

A: Listand List<Object>can store any type of data, Listand List<Object>the only difference is that Listthe type of security check will not trigger compiler, such as the List<String>assignment to Listbe no problem, but assigned to List<Object>will not work, as shown below:

List<String> list = new ArrayList<>();
list.add("Java");
list.add("Java虚拟机");
list.add("Java中文社群");
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
    String str = (String) iterator.next();
    if (str.equals("Java中文社群")) {
        iterator.remove();
    }
}
while (iterator.hasNext()) {
    System.out.println(iterator.next());
}
System.out.println("Over");

A: The program prints the result Over.
Topic Analysis: Because after the first while loop, iterator.hasNext () return value is false, so do not enter the second cycle, after the last print Over.

9. What is the generic works? Why should type erasure?

A: Generics are implemented by type erasure, type erasure refers to the compiler at compile time, it will erase all the relevant types of information, such as List<String>will become after the build Listtype, the purpose of doing so is ensure they are capable and compatible versions (binary library) before 5 Java.

to sum up

In this article we know the generic advantages: safety, to avoid the type of conversion and improve the readability of the code. The essence of the generic type is parameterized, but after the compiler performs type erasure, so that you can be compatible with Java before 5 binary library. This article also describes the use of iterator (Iterator), the benefits of using an iterator is not concerned about the internal details of the container, traverse different types of containers in the same way.


I welcome the attention of the public number, keyword reply " the Java ", there will be a gift both hands! ! ! I wish you a successful interview ! ! !

% 97% E5% 8F% B7 % E4% BA% 8C% E7% BB% B4% E7% A0% 81.png)

Guess you like

Origin www.cnblogs.com/dailyprogrammer/p/12272743.html