Java Miscellaneous
- Sort a two-dimensional array:
Supposeintervals
is a two-dimensional arrayint[][]
.Arrays.sort( intervals, (a,b)->Integer.compare(a[0], b[0]) );
Note how the lambda expression is writte. Or you can write it as:Arrays.sort( intervals, (a,b)->{return Integer.compare(a[0], b[0]);} );
- Convert a linkedList of array to a two-dimensional array:
Supposemerged
is a linkedlist of array.merged.toArray( new int[merged.size()][] );
.
Note that you must specify the array name as an argument of the functiontoArray()
and the size of the array. - incompatible types: ArrayList<ArrayList
> cannot be converted to List<List >
In Java,List
is an interface, andArrayList
is a concrete class that implements theList
interface. The problem arises because Java's generics are invariant. This meansList<ArrayList<Integer>>
is not considered a subtype ofList<List<Integer>>
, even thoughArrayList<Integer>
is a subtype ofList<Integer>
. To fix the error, use:ArrayList<List<Integer>>();
. loop chars over a string:
For example, we have a String variablestr
, to iterate over its chars:for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); System.out.print(c) }
for (char c : str.toCharArray()) { System.out.print(c); }
Convert values of Map to ArrayList:
HashMap<Integer, String> map = new HashMap<>(); map.put(1, "Apple"); map.put(2, "Banana"); map.put(3, "Cherry"); // Convert values to ArrayList ArrayList<String> list = new ArrayList<>(map.values());
- Char in Java
The char data type in Java is used to store a single 16-bit Unicode character. It has a minimum value of\u0000
(or0
) and a maximum value of\uffff
(or65,535
). In Java, if you attempt to assign a value that is outside the range of the char data type to a char variable, it will result in a compilation error. To convert a char arrayca
to string, simply usenew String(ca)
. Fill a two dimensional array with the same value
In order to fill a multidimensional array, we use the for loop to fill each row of the multidimensional array. For example, if we want to fill a two dimensional arraydp
with-1
, we could do:int[][] dp = new int[2001][2001]; for(int i=0;i<dp.length;i++) Arrays.fill( dp[i], -1 );
- remove() in ArrayList
For datatypeArrayList
, there are two commonly used overloads of the methodremove()
as below.remove(int index)
: This method removes the element at the specified position in the list.remove(Object o)
: This method removes the first occurrence of the specified element from the list, if it is present. If you have anArrayList<Integer>
and you callremove
with anint
argument, you are actually callingremove(int index)
. This is because Java chooses the most specific method applicable, andint
is a more specific match forint index
than forObject
. If we want to callremove(Object o)
, we can callremove(Integer.valueOf(num))
. To generate random numbers
Math.random()
: This method returns a pseudorandom double greater than or equal to 0.0 and less than 1.0.java.util.Random.nextInt()
: get the next random integer value from this random number generator’s sequence.java.util.Random.nextInt(int n)
: ThenextInt(int n)
is used to get a random number between0
(inclusive) and the number passed in this argument(n
), exclusive. For example:Random ran = new Random(); int nxt = ran.nextInt(10);
Split String
split( String regex, int limit)
: breaks a given string around matches of the given regular expression. After splitting against the given regular expression, this method returns a string array.
The limit parameter can have 3 values:- limit > 0 – If this is the case, then the pattern will be applied at most limit-1 times, the resulting array’s length will not be more than n, and the resulting array’s last entry will contain all input beyond the last matched pattern.
- limit < 0 – In this case, the pattern will be applied as many times as possible, and the resulting array can be of any size.
- limit = 0 – In this case, the pattern will be applied as many times as possible, the resulting array can be of any size, and trailing empty strings will be discarded.
Example:
String str = "geekss@for@geekss"; String[] arrOfStr = str.split("@", 2); for (String a : arrOfStr) System.out.println(a);
Result:
geekss for@geekss
Compare two strings
s1.compareTo(s2)
:-1
ifs1<s2
0
ifs1==s2
1
ifs1>s2
Note that:
==
: tests for reference equality (whether they are the same object)..equals()
: tests for value equality (whether they contain the same data).
// These two have the same value new String("test").equals("test") // --> true // ... but they are not the same object new String("test") == "test" // --> false // ... neither are these new String("test") == new String("test") // --> false // ... but these are because literals are interned by // the compiler and thus refer to the same object "test" == "test" // --> true // ... string literals are concatenated by the compiler // and the results are interned. "test" == "te" + "st" // --> true
- Convert
String
toint
Integer.valueOf( s )
, orInteger.parseInt( s )
. Initialize a
Queue
SinceQueue
is an interface, you cannot instantiate it directly. Instead, you use one of its implementing classes. A commonly used class for implementing Queue isLinkedList
, which provides FIFO (first-in, first-out) queue operations. Another class you might use for a queue isArrayDeque
, because it uses a resizable array, which can provide better performance for large numbers of elements. However, it does not support null elements.Queue<Integer> queue = new LinkedList<>(); queue.offer(2); int firstElement = queue.poll();
Replace an element in a ArrayList
set(int index, Object element)
, for example:ArrayList<String> list = new ArrayList<>(); list.add("A"); list.set(0, "E");
Get the smallest greater integer of division of two integers
Suppose we have two integersa
andb
, we want to get the smallest greater integer ofa/b
:int sgi = (int)Math.ceil( (double)a/b );
Note that we have to use two castings
double
andint
above.substring
in Javapublic String substring(int begIndex);
: The substring begins with the character at the specified index and extends to the end of this string.public String substring(int begIndex, int endIndex);
: The substring begins with the character at the specified index and extends to the end of this string or up to endIndex – 1 if the second argument is given. beginIndex: the begin index, inclusive. endIndex: the end index, exclusive.
StringBuilder
in Java- to append:
public StringBuilder append(char a);
- to insert at given position:
insert(index, str);
- to delete a substring:
public StringBuilder delete(int start, int end);
- to reverse the order:
StringBuilder reverseStr = str.reverse();
- to get char array:
str.toCharArray();
- to convert to a
String
:str.toString();
Note that to initialize a
StringBuilder
class with achar
, we must convert toString
to use the constructor:StringBuilder sb = new StringBuilder( String.valueOf(c) );
- to append:
Convert
string
toint
Integer.valueOf()
;Integer.parseInt()
.
Arrays.sort an
int
one-dimensional array
Note that Java'sArrays.sort
method that takes a Comparator as an argument is only applicable to arrays of objects, not arrays of primitives.
For example, the following code works:int[][] intervals = new int[10][10]; Arrays.sort(intervals, (a, b) -> Integer.compare(a[0], b[0]));
However, the following code DOES NOT work:
int[] freq = new int[26]; Arrays.sort(freq, (i1, i2) -> Integer.compare(i2, i1));
Also note that
Collections.reverseOrder()
only applies to object.Pair
class in Java
Definition:Pair<Key Type, Value Type> var_name = new Pair<>(key, value);
Example:Pair p1 = new Pair(3, 4);
Method:getKey()
, It returns the key for the pair;getValue()
, It returns a value for the pair..Initialization of Array
Queue<int[]> q = new LinkedList<>(); q.add(new int[] { 1,2 });
In Java, everything is pass-by-value
Read this article for detailed explanation.
The Java Spec says that everything in Java is pass-by-value. There is no such thing as "pass-by-reference" in Java.
The key to understanding this is that something likeDog myDog;
is not a Dog; it's actually a pointer to a Dog. The use of the term "reference" in Java is very misleading and is what causes most of the confusion here. What they call "references" act/feel more like what we'd call "pointers" in most other languages.
What that means, is when you haveDog myDog = new Dog("Rover"); foo(myDog);
you're essentially passing the address of the created
Dog
object to thefoo
method.
Suppose theDog
object resides at memory address 42. This means we pass 42 to the method.
If the Method were defined aspublic void foo(Dog someDog) { someDog.setName("Max"); // AAA someDog = new Dog("Fifi"); // BBB someDog.setName("Rowlf"); // CCC }
Let's look at what's happening.
- the parameter
someDog
is set to the value 42 at line "AAA"
someDog
is followed to theDog
it points to (theDog
object at address 42)- that
Dog
(the one at address 42) is asked to change his name toMax
at line "BBB"
- a new
Dog
is created. Let's say he's at address 74 - we assign the parameter
someDog
to 74
- a new
at line "CCC"
someDog is followed to the
Dogit points to (the
Dog` object at address 74)- that
Dog
(the one at address 74) is asked to change his name toRowlf
Now let's think about what happens outside the method:
DidmyDog
change?
Keeping in mind thatmyDog
is a pointer, and not an actualDog
, the answer is NO.myDog
still has the value 42; it's still pointing to the originalDog
(but note that because of line "AAA", its name is now "Max" - still the same Dog; myDog's value has not changed.)
It's perfectly valid to follow an address and change what's at the end of it; that does not change the variable, however.- the parameter
- In Java, casting of
int
tochar
Given a char:char c = 'C';
, to get the index:int id = c-'A'
. There is no need to do the casting here, because Java will use the ASCII value to do the computation. Note thatInteger.valueOf('1')
andInteger.valueOf("1")
will output different values:Integer.valueOf('1')
returns the ASCII value which is49
, whileInteger.valueOf("1")
returns1
. To get achar
from anint
, we need to do the casting using(char)
:char c = (char) ('A'+1);
. - HashMap operations
Given a hashmap:Map<String, List<String>> map = new HashMap();
,map.getOrDefault("A", new ArrayList<String>()).add(B");
will NOT create the key-value pair in the map. Instead, we need to use:map.computeIfAbsent(cur, k -> new ArrayList<String>()).add(target);
. Given an arraylistList<String> l = new ArrayList<>(List.of("A","B","A"));
, if there are multiple of an item, to remove all of this item, we have to use:while( tmp.remove("A") ) ;
.
The post is published under CC 4.0 License.