Why does Collections.sort use Mergesort but Arrays.sort does not?

The API guarantees a stable sorting which Quicksort doesn’t offer. However, when sorting primitive values by their natural order you won’t notice a difference as primitive values have no identity. Therefore, Quicksort can used for primitive arrays and will be used when it is considered more efficient¹. For objects you may notice, when objects with … Read more

Map.clear() vs new Map : Which one will be better? [duplicate]

Complicated question. Let’s see what happens. You instantiate a new instance, which is backed with new array. So, garbage collector should clear all the key and values from the previous map, and clear the reference to itself. So O(n) algorithm is executed anyway, but in the garbage collector thread. For 1000 records you won’t see … Read more

Difference between Dictionary and Hashtable [duplicate]

Simply, Dictionary<TKey,TValue> is a generic type, allowing: static typing (and compile-time verification) use without boxing If you are .NET 2.0 or above, you should prefer Dictionary<TKey,TValue> (and the other generic collections) A subtle but important difference is that Hashtable supports multiple reader threads with a single writer thread, while Dictionary offers no thread safety. If … Read more

Removing items from a list [duplicate]

for (Iterator<String> iter = list.listIterator(); iter.hasNext(); ) { String a = iter.next(); if (…) { iter.remove(); } } Making an additional assumption that the list is of strings. As already answered, an list.iterator() is needed. The listIterator can do a bit of navigation too. –——— Update As @AyushiJain commented, there is list.removeIf(…);

Collections.sort with multiple fields

(originally from Ways to sort lists of objects in Java based on multiple fields) Original working code in this gist Using Java 8 lambda’s (added April 10, 2019) Java 8 solves this nicely by lambda’s (though Guava and Apache Commons might still offer more flexibility): Collections.sort(reportList, Comparator.comparing(Report::getReportKey) .thenComparing(Report::getStudentNumber) .thenComparing(Report::getSchool)); Thanks to @gaoagong’s answer below. Note … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)