current position:Home>2022java interview questions complete, with answers, latest arrangement

2022java interview questions complete, with answers, latest arrangement

2022-06-24 09:22:26m0_ sixty-one million eighty-three thousand four hundred and ni

1. Traverse ArrayList How to remove an element correctly

Example of wrong writing :

public static void remove(ArrayList<String> list) { for (int i = 0; i < list.size(); i++) { String s = list.get(i);if (s.equals("bb")) { list.remove(s);}}}

Example 2 of wrong writing :

public static void remove(ArrayList<String> list) { for (String s : list) { if (s.equals("bb")) { list.remove(s);}}}

The only way to analyze the causes of the above-mentioned errors is to turn it over jdk Of ArrayList Source code , Let's take a look at ArrayList Medium remove Method ( Be careful ArrayList Medium remove There are two methods of the same name , It's just different , What we are looking at here is to join the ginseng Object Of remove Method ) How did it happen :

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;}

Follow the general execution path to else The final call under the path faseRemove Method :

private void fastRemove(int index) { modCount++;int numMoved = size - index - 1;if (numMoved > 0)System.arraycopy(elementData, index+1, elementData, index,numMoved);elementData[--size] = null;// Let gc do its work}

You can see that it will execute System.arraycopy Method , Causes the deletion of elements to involve the movement of array elements . For the wrong way to write one , After traversing the second element string bb Because the deletion conditions are met , So remove the element from the array , And move the next element ( It's also a string bb) To the current position , Causes the next loop to traverse the next string bb It doesn't traverse to , So can't delete . In this case, it can be removed in reverse order to avoid :

public static void remove(ArrayList<String> list) { for (int i = list.size() - 1; i >= 0; i--) { String s = list.get(i);if (s.equals("bb")) { list.remove(s);}}}

Because even if the element deletion occurs during the array reverse traversal, the subsequent element traversal will not be affected .

And the reason for error two is foreach The way of writing is practical Iterable、hasNext、next Method shorthand , The problem is also in the above fastRemove In the method , You can see the first line modCount Add one... To the value of the variable , But in ArrayList Iterator returned ( The code is in its parent class AbstractList in ):

public Iterator<E> iterator() { return new Itr();}

What's back here is AbstractList The iterator implementation inside the class private class Itr implements Iterator, Look at this kind of next Method :

public E next() { checkForComodification();try { E next = get(cursor);lastRet = cursor++;return next;} catch (IndexOutOfBoundsException e) { checkForComodification();throw new NoSuchElementException();}}

first line checkForComodification Method :

final void checkForComodification() { if (modCount != expectedModCount)throw new ConcurrentModificationException();}

We will check the number of internal changes of the iterator , Because of the above remove(Object) The method has been modified modCount Value , So the concurrent modification exception will be reported . To avoid this, use iterator iterations ( To display or foreach Implicit ) Do not use ArrayList Of remove, Instead of using Iterator Of remove that will do .

public static void remove(ArrayList<String> list) { Iterator<String> it = list.iterator();while (it.hasNext()) { String s = it.next();if (s.equals("bb")) { it.remove();}}}

2. say ArrayList The expansion mechanism of

ArrayList The essence of expansion is to calculate a new expansion array size After instantiation , And copy the contents of the original array to the new array .

public boolean add(E e) { // Capacity expansion ensureCapacityInternal(size + 1);// Increments modCount!!elementData[size++] = e;return true;}private void ensureCapacityInternal(int minCapacity) { ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));}

private static int calculateCapacity(Object[] elementData, int minCapacity) { // If an empty array is passed in, the minimum capacity is taken as the default capacity and minCapacity Maximum value between if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) { return Math.max(DEFAULT_CAPACITY, minCapacity);}return minCapacity;}private void ensureExplicitCapacity(int minCapacity) { modCount++;// If the minimum required space ratio elementData You need more memory space , You need to expand // overflow-conscious codeif (minCapacity - elementData.length > 0)grow(minCapacity);}private void grow(int minCapacity) { // obtain elementData The memory space length of the array int oldCapacity = elementData.length;// Expand to the original 1.5 times int newCapacity = oldCapacity + (oldCapacity >> 1);// Check whether the capacity is enough if (newCapacity - minCapacity < 0)newCapacity = minCapacity;// If the default value is greater than the default maximum value , Check for spillage if (newCapacity - MAX_ARRAY_SIZE > 0)newCapacity = hugeCapacity(minCapacity);// call Arrays.copyOf Methods will elementData Array points to new memory space // And will elementData Copy the data to the new memory space elementData = Arrays.copyOf(elementData, newCapacity);}

3. HashMap How to solve the hash conflict

Hashmap solve hash Conflict , The chain address method is used , It's an array + In the form of linked list .put Execution first judgment table[i] Location , If it is empty, insert it directly , If it is not null, judge whether it is equal to the current value , Equality covers , If not equal , Determine whether it is a red black tree node , If not , From table[i] The position begins to traverse the list , Equal coverage , Unequal insertion .

4. String Common methods of the class have those ?

  • indexOf(): Returns the index of the specified character .
  • charAt(): Returns the character at the specified index .
  • replace(): String substitution .
  • trim(): Removes white space at both ends of the string .
  • split(): Split string , Returns a split array of strings .
  • getBytes(): Return string byte Type array .
  • length(): Return string length .
  • toLowerCase(): Converts a string to lowercase .
  • toUpperCase(): Converts a string to an uppercase character .
  • substring(): Intercepting string .
  • equals(): String comparison .

5. sketch Java The set in

  1. Collection Next :List system ( Orderly 、 Element allows repetition ) and Set system ( disorder 、 Elements do not repeat )“set according to equals and hashcode Judge , An object to be stored in Set in , Must be rewritten equals and hashCode Method ”
  2. Map Next :HashMap Thread out of sync ;TreeMap Thread synchronization
  3. Collection Series and Map series :Map It's right Collection A supplement to , It doesn't matter

“ The following questions , You can think for yourself first . Besides, I put all Java The relevant interview questions and answers have been sorted out , Private letter needed , You can get it for free !

6. EnumSet What is it? ?

7. establish String What are the different ways of objects ?

8. why Map Interface non-inheritance Collection Interface ?

9. HashMap and Hashtable The difference between

10. ArrayList and HashMap Default size

11. LinkedList Is it a one-way list or a two-way list

12. When a set is passed as an argument to a function , How to make sure that the function can't modify it ?

13. stay Java in ,HashMap How it works ?

14. TreeMap and TreeSet How to compare elements in sorting ?Collections In a tool class sort() Method how to compare elements ?

15. HashSet and TreeSet What's the difference? ?

16. String What are the benefits of being immutable ?

17. Java What are the best practices for a collection class framework ?

18. HashSet How do you make sure you don't repeat

19. HashMap Implementation principle of

20. Iterater and ListIterator What's the difference between ?

21. What are queues and stacks , List their differences ?

22. HashMap Is thread safe ?

23. Write a piece of code to traverse ArrayList Remove an element

24. Is there any order Map Implementation class , If there is , How do they keep order

25. ArrayList,Vector,LinkedList Storage performance and characteristics of

26. What is string pool ?

27. Which collection classes provide random access to elements ?

28. hashCode() and equals() How important is the method ?

29. Can we use any class as Map Of key?

30. # summary

31. What are the advantages of generics in a collection framework ?

32. ArrayList and Vector What are the similarities and differences ?

33. HashMap,HashTable,ConcurrentHash Common ground and difference of

34. Set The elements in can't be repeated , So how to distinguish repetition from non repetition Yes, it is == still equals()

35. Java What is the difference between synchronous and concurrent collections in

36. String str="i" And String str=new String(“i”) Are they exactly alike? ?

37. How many objects are created in the following statement :String s=“a”+“b”+“c”+“d”

38. If you want to use Object As hashMap Of Key?;

39. Java What are the classes of the operation strings in ? What's the difference between them ?

40. Let's talk about thread pool blocking queues ~

41. Java What is a collection framework ? Name some of the advantages of the collection framework ?

42. And Java What are the best practices related to the collection framework ?

43. TreeMap Bottom ?

44. ArrayList and LinkedList What's the difference ?

45. How do we create a from a given set synchronized Set ?

46. Java How to print array in ?

47. When a set is passed as an argument to a function , How to make sure that the function can't modify it ?

48. How to choose HashMap still TreeMap?

49. HashMap summary

50. Give voice ArrayList,LinkedList Storage performance and characteristics of

51. Collections What is the class ?

52. Comparator and Comparable The difference between

53. Iterator and ListIterator What's the difference ?

54. List、Map、Set Three interfaces , When accessing elements , What are the characteristics of each ?

55. Comparable and Comparator What's the difference between interfaces ?

56. Map What are the different collection views provided by the interface ?

57. Which collection classes are thread-safe ? What's not safe ?

58. By iterator fail-fast attribute , What do you understand ?

59. HashMap and HashTable What's the difference? ?

60. why Iterator There is no concrete implementation of the interface ?

61. How to implement collection sorting

62. How to compare two strings ?

63. Talk about the characteristics of red and black trees ?

64. Traverse a List What are the different ways ?

65. What are the general algorithms implemented in the collection framework ?

66. UnsupportedOperationException What is it? ?

67. Why not like Iterator.add() This way , Add elements to the collection ?

68. How to implement array and List Conversion between ?

69. Collection And Collections What's the difference ?

70. LinkedHashMap Application , Bottom , principle

71. ArrayList and HashMap The default size of is most ?

72. HashMap Automatic expansion

73. HashMap stay JDK1.7 and JDK1.8 What are the differences between ?

74. What is? String, What data type is it ?

75. Set The elements in can't be repeated , So what is the method to distinguish repetition from non repetition == still equals() What's the difference between them

76. ArrayList and Vector The difference between

77. When iterating over a set , How to avoid ConcurrentModificationException?

78. How to judge two String Whether it is equal or not ?

79. LinkedHashMap and PriorityQueue The difference between

80. String s = new String(“xyz”); Created several StringObject? Can I inherit String class

81. HashMap Why not use it directly hashCode() The processed hash value is directly used as table The subscript ?

82. Collections.sort and Arrays.sort Implementation principle of

83. Why doesn't an iterator have a way to get the next element directly , Without moving the cursor ?

84. How to print array contents

85. uppercase O What is it? ? Take a few examples ?

86. Why? HashMap in String、Integer This kind of packing class is suitable for key?

87. How to integrate String Convert to byte array, On the contrary ?

88. BlockingQueue What is it? ?

89. Implementation of blocking queue ,ArrayBlockingQueue The underlying implementation of ?

90. How to split a String?

91. Array and ArrayList What's the difference ? When is it more suitable to use Array?

92. How to make a string lowercase or uppercase ?

93. The way HashSet Implementation principle of ?

94. iterator Iterator What is it? ? How to use it? , What are the characteristics of ?

95. fail-fast And fail-safe What's the difference? ?

96. ArrayList and LinkedList difference ?

97. String、StringBuffer and StringBuilder difference ( Similar to the previous question )

98. How to ensure that a set cannot be modified ?

99. Iterator What is it? ?

100. ArrayList and LinkedList The difference between

101. ArrayList Set join 1 Ten thousand data , How to improve efficiency

102. Why introduce SpringBuffer、StringBuilder Two string processing classes

103. HashMap How to realize the expansion operation of ?

104. What is? Java Priority queue (Priority Queue)?

105. ArrayList and Array What's the difference?

106. ConcurrentHashMap and Hashtable The difference between ?

107. Comparable and Comparator What is the interface ?

108. HashMap Why is the length of 2 Power square , And other definitions of constants ~

109. ConcurrenHashMap principle ?1.8 Why should we use red and black trees in China ?

110. Java What are the basic interfaces of the collection framework ?

111. Enumeration and Iterator Interface differences ?

112. How do we sort a set of objects ?

113. WeakHashMap And HashMap What's the difference

114. How to integrate String Convert to char, On the contrary ?

115. What are concurrent collection classes ?

116. poll() Methods and remove() Method difference

117. Java Sets in and their inheritance relationships

118. why Collection Not from Cloneable and Serializable Interface inheritance ?

119. HashMap Of put The specific process of the method ?

120. TreeMap Implementation principle of

121. How to Object Of list Sort

122. Array and ArrayList What's the difference ?

Partners who need the latest interview information above , After paying attention to the private message “ need ”, You can get it for free !

copyright notice
author[m0_ sixty-one million eighty-three thousand four hundred and ni],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/175/202206240758494741.html

Random recommended