Tuesday, June 27, 2017

Copying sets Java

Another way to do this is to use the copy constructor:
Collection<E> oldSet = ...
TreeSet<E> newSet = new TreeSet<E>(oldSet);
Or create an empty set and add the elements:
Collection<E> oldSet = ...
TreeSet<E> newSet = new TreeSet<E>();
newSet.addAll(oldSet);
Unlike clone these allow you to use a different set class, a different comparator, or even populate from some other (non-set) collection type.

Nested iterating through list followed by an eventual deletion

I'm trying to iterate throuh a list while already looping through it (nested loops). Consider the code below:
ArrayList<Integer> list = new ArrayList<Integer>(); // add some values to it

for(int i : list) { // ConcurrentModificationException

   Iterator iterator = list.iterator();

   while(iterator.hasNext()) {

      int n = iterator.next();

      if(n % i == 0) {
         iterator.remove();
      }

   }

}
The example above results in a ConcurrentModificationException. The condition to remove an element is, of course, just an example.
I'm sure I'm just missing something; but how should I construct a loop that achieves the same thing in Java without throwing an exception?
 
----------------------------------------------------------
Obviously modifying list when you iterate over it causing the execption. You can use another list to maintain the list of elements to be removed and remove them at the end.
ArrayList<Integer> list = new ArrayList<Integer>(); // add some values to it
ArrayList<Integer> del = new ArrayList<Integer>(); // Elements to be deleted

for(int i : list) { // ConcurrentModificationException
   Iterator iterator = list.iterator();
   while(iterator.hasNext()) {    
      int n = iterator.next();
      if(n % i == 0) {
          del.add(n);      
      }
   }
}

list.removeALL(del);
 

Monday, June 26, 2017

Here is a code sample to use the iterator in a for loop to remove the entry.

    Map<String, String> map = new HashMap<String, String>() {
      {
        put("test", "test123");
        put("test2", "test456");
      }
    };

    for(Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); it.hasNext(); ) {
      Map.Entry<String, String> entry = it.next();
      if(entry.getKey().equals("test")) {
        it.remove();
      }
    }

Tuesday, June 20, 2017

BigInteger Class in Java

BigInteger class is used for mathematical operation which involves very big integer calculations that are outside the limit of all available primitive data types.
For example factorial of 100 contains 158 digits in it so we can’t store it in any primitive data type available. We can store as large Integer as we want in it. There is no theoretical limit on the upper bound of the range because memory is allocated dynamically but practically as memory is limited you can store a number which has Integer.MAX_VALUE number of bits in it which should be sufficient to store mostly all large values.
Below is an example Java program that uses BigInteger to compute Factorial.
// Java program to find large factorials using BigInteger
import java.math.BigInteger;
import java.util.Scanner;
 
public class Example
{
    // Returns Factorial of N
    static BigInteger factorial(int N)
    {
        // Initialize result
        BigInteger f = new BigInteger("1"); // Or BigInteger.ONE
 
        // Multiply f with 2, 3, ...N
        for (int i = 2; i <= N; i++)
            f = f.multiply(BigInteger.valueOf(i));
 
        return f;
    }
 
    // Driver method
    public static void main(String args[]) throws Exception
    {
        int N = 20;
        System.out.println(factorial(N));
    }
}
Output:
2432902008176640000
If we have to write above program in C++, that would be too large and complex, we can look at Factorail of Large Number.
In this way BigInteger class is very handy to use because of its large method library and it is also used a lot in competitive programming.
Now below is given a list of simple statements in primitive arithmetic and its analogous statement in terms of BigInteger objects.
Declaration
int a, b;    
BigInteger A, B; 
Initialization:
 
a = 54;
b = 23;
A  = BigInteger.valueOf(54);
B  = BigInteger.valueOf(37); 
And for Integers available as string you can initialize them as:
A  = new BigInteger(“54”);
B  = new BigInteger(“123456789123456789”); 
Some constant are also defined in BigInteger class for ease of initialization :
A = BigInteger.ONE;
// Other than this, available constant are BigInteger.ZERO 
// and BigInteger.TEN 
Mathematical operations:
int c = a + b;
BigInteger C = A.add(B); 
Other similar function are subtract() , multiply(), divide(), remainder()
But all these function take BigInteger as their argument so if we want these operation with integers or string convert them to BigInteger before passing them to functions as shown below:
String str = “123456789”;
BigInteger C = A.add(new BigInteger(str));
int val  = 123456789;
BigInteger C = A.add(BigIntger.valueOf(val)); 
Extraction of value from BigInteger:
int x   =  A.intValue();   // value should be in limit of int x
long y   = A.longValue();  // value should be in limit of long y
String z = A.toString();  

Comparison:

if (a < b) {}   // For primitive int
if (A.compareTo(B) < 0)  {} // For BigInteger 
Actually compareTo returns -1(less than), 0(Equal), 1(greater than) according to values.
For equality we can also use:
if (A.equals(B)) {}  // A is equal to B 
Related Articles:
Large Fibonacci Numbers in Java
BigInteger class also provides quick methods for prime numbers.
SPOJ Problems:
So after above knowledge of function of BigInteger class, we can solve many complex problem easily, but remember as BigInteger class internally uses array of integers for processing, the operation on object of BigIntegers are not as fast as on primitives that is add function on BigIntgers doesn’t take constant time it takes time proportional to length of BigInteger, so complexity of program will change accordingly. Below are SPOJ problems to get a grasp on BigIntegers –
http://www.spoj.com/problems/JULKA/
http://www.spoj.com/problems/MCONVERT/en/
http://www.spoj.com/problems/MUL2COM/en/
http://www.spoj.com/problems/REC/
http://www.spoj.com/problems/SETNJA/en/
http://www.spoj.com/problems/TREE/
http://www.spoj.com/problems/WORMS/

Large Numbers in Java

You can use the BigInteger class for integers and BigDecimal for numbers with decimal digits. Both classes are defined in java.math package.
Example:
BigInteger reallyBig = new BigInteger("1234567890123456890");
BigInteger notSoBig = new BigInteger("2743561234");
reallyBig = reallyBig.add(notSoBig);

Wednesday, June 14, 2017

What are the Xms and Xmx parameters when starting JVMs?

 

The flag Xmx specifies the maximum memory allocation pool for a Java Virtual Machine (JVM), while Xms specifies the initial memory allocation pool.
This means that your JVM will be started with Xms amount of memory and will be able to use a maximum of Xmx amount of memory. For example, starting a JVM like below will start it with 256MB of memory, and will allow the process to use up to 2048MB of memory:
java -Xmx2048m -Xms256m
The memory flag can also be specified in multiple sizes, such as kilobytes, megabytes, and so on.
-Xmx1024k
-Xmx512m
-Xmx8g
The Xms flag has no default value, and Xmx typically has a default value of 256MB. A common use for these flags is when you encounter a java.lang.OutOfMemoryError.
When using these settings, keep in mind that these settings are for the JVM's heap, and that the JVM can/will use more memory than just the size allocated to the heap. From Oracle's Documentation:
Note that the JVM uses more memory than just the heap. For example Java methods, thread stacks and native handles are allocated in memory separate from the heap, as well as JVM internal data structures.