Aug 7, 2018
String
String.substring()
String.substring()
The java string substring() method returns a part of the string.
We pass begin index
and end index
number position in the java substring method where start index is inclusive and end index is exclusive. In other words, start index starts from 0 whereas end index starts from 1.
You can get substring from the given string object by one of the two methods:
public String substring(int startIndex)
: This method returns new String object containing the substring of the given string from specified startIndex (inclusive).public String substring(int startIndex, int endIndex)
: This method returns new String object containing the substring of the given string from specified startIndex to endIndex.
In case of string:
startIndex: inclusive
endIndex: exclusive
Example:
Output:
String
vs StringBuilder
vs StringBuffer
String
vs StringBuilder
vs StringBuffer
Consider below code with three concatenation functions with three different types of parameters, String, StringBuffer and StringBuilder.
Output:
Explanation:
Concat1 : In this method, we pass a string "Geeks" and perform "
s1 = s1 + "forgeeks"
". The string passed frommain()
is not changed, this is due to the fact that String is immutable. Altering the value of string creates another object and s1 inconcat1()
stores reference of new string. References s1 inmain()
andconcat1()
refer to different strings.Concat2 : In this method, we pass a string "Geeks" and perform "
s2.append("forgeeks")
" which changes the actual value of the string (in main) to "Geeksforgeeks
". This is due to the simple fact that StringBuilder is mutable and hence changes its value.Concat3 : StringBuffer is similar to StringBuilder except one difference that StringBuffer is thread safe, i.e., multiple threads can use it without any issue. The thread safety brings a penalty of performance.
When to use which one :
If a string is going to remain constant throughout the program, then use String class object because a String object is immutable.
If a string can change (example: lots of logic and operations in the construction of the string) and will only be accessed from a single thread, using a StringBuilder is good enough.
If a string can change, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous so you have thread-safety.
Map
java.util.HashMap.containsKey()
java.util.HashMap.containsKey()
The java.util.HashMap.containsKey()
method is used to check whether a particular key is being mapped into the HashMap or not. It takes the key element as a parameter and returns True if that element is mapped in the map.
Syntax:
Parameters: The method takes just one parameter key_element that refers to the key whose mapping is supposed to be checked inside a map.
Return Value: The method returns boolean true if the presence of the key is detected else false .
Below programs are used to illustrate the working of java.util.HashMap.containsKey()
Method:
Program 1: Mapping String Values
to Integer Keys
.
Output:
Program 2: Mapping Integer Values
to String Keys
.
Output:
HashMap
vs. TreeMap
vs. HashTable
vs. LinkedHashMap
HashMap
vs. TreeMap
vs. HashTable
vs. LinkedHashMap
Map Overview
There are 4 commonly used implementations of Map in Java SE - HashMap
, TreeMap
, Hashtable
and LinkedHashMap
. If we use one sentence to describe each implementation, it would be the following:
HashMap
is implemented as a hash table, and there is no ordering on keys or values.TreeMap
is implemented based on red-black tree structure, and it is ordered by the key.LinkedHashMap
preserves the insertion order.Hashtable
is synchronized, in contrast to HashMap.
This gives us the reason that HashMap
should be used if it is thread-safe, since Hashtable
has overhead for synchronization.
TreeMap
TreeMap
A TreeMap
is sorted by keys. Let's first take a look at the following example to understand the "sorted by keys" idea.
Output:
Since TreeMaps
are sorted by keys, the object for key has to be able to compare with each other, that's why it has to implement Comparable
interface. For example, you use String as key, because String implements Comparable interface. Let's change the Dog, and make it comparable.
Output:
It is sorted by key, i.e., dog size in this case. If "Dog d4 = new Dog("white", 10);
" is replaced with "Dog d4 = new Dog("white", 40);
", the output would be:
The reason is that TreeMap
now uses compareTo()
method to compare keys. Different sizes make different dogs!
HashMap
HashMap
If key of the HashMap
is self-defined objects
, then equals()
and hashCode()
contract need to be followed.
Output:
Note here, we add "white dogs" twice by mistake, but the HashMap
takes it. This does not make sense, because now we are confused how many white dogs are really there. The Dog class should be defined as follows:
Now the output is:
The reason is that HashMap doesn't allow two identical elements. By default, the hashCode()
and equals()
methods implemented in Object class are used. The default hashCode()
method gives distinct integers for distinct objects, and the equals()
method only returns true when two references refer to the same object. Check out the hashCode() and equals() contract
if this is not obvious to you.
LinkedHashMap
LinkedHashMap
LinkedHashMap
is a subclass of HashMap
. That means it inherits the features of HashMap. In addition, the linked list preserves the insertion-order. Let's replace the HashMap with LinkedHashMap using the same code used for HashMap.
Output is:
The difference is that if we use HashMap
the output could be the following - the insertion order is not preserved.
Hashtable
Hashtable
From Java Doc: The HashMap class is roughly equivalent to Hashtable
, except that it is unsynchronized and permits nulls
.
KMP
Last updated