Java collection interview questions sorting, [performance optimization practice]

Posted by Matt Kindig on Mon, 20 Dec 2021 22:27:08 +0100

Differences between HashMap and ConcurrentHashMap

  1. ConcurrentHashMap divides the whole bucket array into segments, and then protects each segment with a lock lock. Compared with the synchronized lock of HashTable, the granularity of the lock is finer and the concurrency performance is better. However, HashMap has no lock mechanism and is not thread safe. (after JDK1.8, ConcurrentHashMap enables a new way to implement it, using CAS algorithm.)

  2. null is allowed for key value pairs of HashMap, but not for concurrent HashMap.

How does HashSet check for duplicates

When you add an object to the HashSet, the HashSet will first calculate the hashcode value of the object to determine the location of the object. At the same time, it will also compare with the hashcode values of other added objects. If there is no matching hashcode, the HashSet will assume that the object does not appear repeatedly. However, if an object with the same hashcode value is found, the equals () method will be called to check whether the objects with the same hashcode are really the same. If they are the same, the HashSet will not make the join operation successful. (excerpted from my java enlightenment book head first Java, Second Edition)

Relevant provisions of hashCode() and equals():

  1. If two objects are equal, the hashcode must be the same

  2. If two objects are equal, return true for two equals methods

  3. Two objects have the same hashcode value, and they are not necessarily equal

  4. To sum up, if the equals method is overridden, the hashCode method must also be overridden

  5. The default behavior of hashCode() is to generate unique values for objects on the heap. If hashCode() is not overridden, the two objects of the class will not be equal in any case (even if they point to the same data).

==Difference from equals

  1. ==Determines whether two variables or instances point to the same memory space. equals determines whether the values of the memory space pointed to by two variables or instances are the same

  2. ==It refers to the comparison of memory addresses. equals() compares the contents of strings. 3== Refers to whether the references are the same. Equals () refers to whether the values are the same

What is the difference between comparable and comparator?

  • The comparable interface is actually from Java Lang package, which has a compareTo(Object obj) method for sorting

  • The comparator interface is actually from Java Util package, which has a compare(Object obj1, Object obj2) method for sorting

Generally, when we need to use custom sorting for a collection, we need to override the compareTo method or compare method. When we need to implement two sorting methods for a collection, such as one sorting method for song name and singer name in a song object, We can rewrite the compareTo method and use the self-made Comparator method, or use two comparators to sort song names and star names. The second means that we can only use two parameter versions of collections sort().

Comparator custom sorting

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;



/**

 * TODO Collections Sorting of class method tests

 * @author Kou Shuang

 * @date 2017 November 20

 * @version 1.8

 */

public class CollectionsSort {



	public static void main(String[] args) {



		ArrayList<Integer> arrayList = new ArrayList<Integer>();

		arrayList.add(-1);

		arrayList.add(3);

		arrayList.add(3);

		arrayList.add(-5);

		arrayList.add(7);

		arrayList.add(4);

		arrayList.add(-9);

		arrayList.add(-7);

		System.out.println("Original array:");

		System.out.println(arrayList);

		// Void reverse (list): reverse

		Collections.reverse(arrayList);

		System.out.println("Collections.reverse(arrayList):");

		System.out.println(arrayList);

/*		

		 * void rotate(List list, int distance),Rotate.

		 * When distance is a positive number, move the last distance elements of the list to the front as a whole. When distance is negative, the

		 * list Move the first distance element of to the back as a whole.

		 

		Collections.rotate(arrayList, 4);

		System.out.println("Collections.rotate(arrayList, 4):");

		System.out.println(arrayList);*/

		

		// Void sort (list), sorted in ascending natural order

		Collections.sort(arrayList);

		System.out.println("Collections.sort(arrayList):");

		System.out.println(arrayList);



		// Void shuffle (list), random sort

		Collections.shuffle(arrayList);

		System.out.println("Collections.shuffle(arrayList):");

		System.out.println(arrayList);



		// Usage of custom sorting

		Collections.sort(arrayList, new Comparator<Integer>() {



			@Override

			public int compare(Integer o1, Integer o2) {

				return o2.compareTo(o1);

			}

		});

		System.out.println("After customized sorting:");

		System.out.println(arrayList);

	}



}

Override the compareTo method to sort by age

package map;



import java.util.Set;

import java.util.TreeMap;



public class TreeMap2 {



	public static void main(String[] args) {

		// TODO Auto-generated method stub

		TreeMap<Person, String> pdata = new TreeMap<Person, String>();

		pdata.put(new Person("Zhang San", 30), "zhangsan");

		pdata.put(new Person("Li Si", 20), "lisi");

		pdata.put(new Person("Wang Wu", 10), "wangwu");

		pdata.put(new Person("Xiao Hong", 5), "xiaohong");

		// Get the value of the key and the corresponding value of the key

		Set<Person> keys = pdata.keySet();

		for (Person key : keys) {

			System.out.println(key.getAge() + "-" + key.getName());



		}

	}

}



// The person object does not implement the Comparable interface, so it must be implemented so that there will be no errors and the data in treemap can be arranged in order

// The String class of the previous example has implemented the Comparable interface by default. For details, you can view the API documentation of the String class. In addition

// For example, the Integer class has implemented the Comparable interface, so there is no need to implement it separately



class Person implements Comparable<Person> {

	private String name;

	private int age;



	public Person(String name, int age) {

		super();

		this.name = name;

		this.age = age;

	}



	public String getName() {

		return name;

	}



	public void setName(String name) {

		this.name = name;

	}



	public int getAge() {

		return age;

	}



	public void setAge(int age) {

		this.age = age;

	}



	/**

	 * TODO Override the compareTo method to sort by age

	 */

	@Override

	public int compareTo(Person o) {

		// TODO Auto-generated method stub

		if (this.age > o.getAge()) {

			return 1;

		} else if (this.age < o.getAge()) {

			return -1;

		}

		return age;

	}

}

How to sort the list of objects?

  • To sort the objects array, we can use arrays Sort() method

  • To sort the collection of objects, you need to use collections Sort() method

How to realize the mutual conversion between array and List?

List to array: toArray(arraylist.size() method; Array to list: asList(a) method of arrays

List<String> arrayList = new ArrayList<String>();

		arrayList.add("s");

		arrayList.add("e");

		arrayList.add("n");

		/**

		 * ArrayList Turn array

		 */

		int size=arrayList.size();

		String[] a = arrayList.toArray(new String[size]);

		//Output second element

		System.out.println(a[1]);//Results: e

		//Output entire array

		System.out.println(Arrays.toString(a));//Result: [s, e, n]

		/**

		 * Array to list

		 */

		List<String> list=Arrays.asList(a);

		/**

		 * list To Arraylist

		 */

		List<String> arrayList2 = new ArrayList<String>();

		arrayList2.addAll(list);

		System.out.println(list);

How to find the intersection union difference set of ArrayList set to duplicate Union

Learn, share and encourage

Here are the learning resources obtained by Xiaobian, including the file sharing of "300 notes of high-frequency test points for intermediate and advanced Java development interview. pdf" and "notes of Java core knowledge system. pdf", which are rich in content, including a large number of knowledge points such as JVM, lock, concurrency, java reflection, Spring principle, microservice, Zookeeper, database, data structure and so on. At the same time, there is also a brain map of knowledge notes for advanced java learning (including a large number of learning notes)!

The materials are provided free of charge, which is not easy to sort out. Friends in need can forward and share them. At the same time, they can pay attention to me, share learning resources regularly, and update some technology sharing!

Free access to information: click here to get it for free!

Sorting is not easy. Thank you for forwarding and support from friends in need!

Java core knowledge system notes pdf

Senior Java development interview high frequency test notes 300 pdf

Brain map of architecture advanced interview topics and architecture learning notes

Java architecture advanced learning video sharing

Materials are provided free of charge. It's not easy to sort them out. Friends in need can forward and share them. At the same time, they can pay attention to me, share learning resources regularly, and update some technology sharing**

Free access to information: click here to get it for free!

Sorting is not easy. Thank you for forwarding and support from friends in need!

Java core knowledge system notes pdf

[external chain picture transferring... (img-fdqF3bXe-1629316536502)]

Senior Java development interview high frequency test notes 300 pdf

[external chain picture transferring... (img-PKB9BMRx-1629316536504)]

Brain map of architecture advanced interview topics and architecture learning notes

[external chain picture transferring... (img-uehfxt9-1629316536505)]

Java architecture advanced learning video sharing

[external chain picture transferring... (img-q8oL5Bz4-1629316536507)]

Topics: Java Interview Programmer