Thursday, August 13, 2015

Java Program to create out of memory exception:

package com.test.memoryLeak;

import java.util.Map;

public class KeylessEntry {
final String s;
KeylessEntry(String s)
{
this.s=s;
}

public static void main(String[] args) {
     try {

     Map map = System.getProperties();
     for(;;) {
     KeylessEntry obj = new KeylessEntry("key");
     map.put(obj, "value");
     }
} catch (Exception e) {
e.printStackTrace();
}
 
  }

}

Output:
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Hashtable.rehash(Hashtable.java:356)
at java.util.Hashtable.put(Hashtable.java:412)
at com.test.memoryLeak.KeylessEntry.main(KeylessEntry.java:18)

Java program to convert array into list:


There is the two way to covert array into list

1. Arrays.asList(strArr) => Will return fix size of array list, means will not able to modify or change. and also if strArr will change then list also got affected because it is the fixed size array and it works for bridge between array and collection api.

If will try to change the list then will return unsupported exception.

2. Collections.addAll(list, strArr) => It will convert and create new copy of list, and also if strArr will change it will not be affected to the list.

Please check below example:


package com.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ArrayToList {

public static void main(String[] args) {
String[] strArr = {"1","2","3"};
List<String> list = new ArrayList<String>();
List<String> collectionList = new ArrayList<String>();
list = Arrays.asList(strArr);
Collections.addAll(collectionList, strArr);
System.out.println(list);
System.out.println(collectionList);
strArr[1] = "7";
collectionList.add("4");
System.out.println(list);
System.out.println(collectionList);

}

}

Output:
[1, 2, 3]
[1, 2, 3]
[1, 7, 3] => got changed
[1, 2, 3, 4] 

No comments: