Public Class Public Static Void: Main Args Coins
Public Class Public Static Void: Main Args Coins
Following example compares the element of a collection by converting a string into a treeset using Collection.min() and
Collection.max() methods of Collection class.
Eg-
System.out.println(Collections.min(set));
System.out.println(Collections.min(set, String.CASE_INSENSITIVE_ORDER));
System.out.println(Collections.max(set));
System.out.println(Collections.max(set,
String.CASE_INSENSITIVE_ORDER));
Following example shows how to make a collection read-only by using Collections.unmodifiableList() method of Collection class.
list = Collections.unmodifiableList(list);
try {
} catch (UnsupportedOperationException e) {
set = Collections.unmodifiableSet(set);
Map map = new HashMap();
map = Collections.unmodifiableMap(map);
Collection cl = hMap.values();
Following example uses hasMoreElements & nestElement Methods of Enumeration Class to display the contents of the
HashTable.
ht.put("1", "One");
ht.put("2", "Two");
ht.put("3", "Three");
Enumeration e = ht.elements();
while(e.hasMoreElements()) {
System.out.println(e.nextElement());
ht.put("1", "One");
ht.put("2", "Two");
ht.put("3", "Three");
Enumeration e = ht.keys();
while (e.hasMoreElements()) {
System.out.println(e.nextElement());
} }
Following example uses indexOfSubList() & lastIndexOfSubList() to check whether the sublist is there in the list or not & to find the
last occurance of the sublist in the list.
How to sort keys in TreeMap by using Comparator with user define objects?
@Override
return e1.getName().compareTo(e2.getName());
} }
class MySalaryComp implements Comparator<Empl>{
@Override
return 1;
} else {
return -1;
} } }
To avoid duplicate user defined objects in TreeSet, you have to implement Comparator interface with equality verification. Below example gives a
sample code to implement it.
How to eliminate duplicate user defined objects from HashSet?
Below example shows how to avoid duplicate user defined objects from HashSet. You can achieve this by implementing equals and hashcode
methods at the user defined objects.
Hashtable implementation with equals and hashcode example.
Below example shows how to use user defined objects as keys. To avoid duplicates keys you have to implement equals and hashcode methods. In
below example we are using Emp object as key, and it has implemented equals, and hashcode methods. Example also enters duplicate object as key,
and you can see that Hashtable eleminates the duplicate keys.
public class MyHashtableUserKeys {
} }
class Emp{
public Emp(int id, String n, int s){ this.id = id; this.name = n; this.salary = s; }
public String toString(){ return "Id: "+this.id+" -- Name: "+this.name+" -- Salary: "+this.salary; }
@Override
System.out.println("In hashcode");
return this.getId(); }
@Override
Emp e = null;
e = (Emp) obj; }
System.out.println("In equals");
if(this.getId() == e.getId()){
return true;
} else {
return false;
} } }
Output:
In hashcode
In hashcode
In hashcode
In hashcode
Fecthing value by creating new key:
In hashcode
In equals
Id: 512 -- Name: Tom -- Salary: 2400 ==> TOM
How to search user defined object from a List by using binary search using comparator?
The Collections.binarySearch() method searches the specified list for the specified user defined object using the binary search algorithm. The list
must be sorted into ascending order according to the specified comparator (as by the sort(List, Comparator) method), prior to making this call. If it is
not sorted, the results are undefined. If the list contains multiple elements equal to the specified object, there is no guarantee which one will be
found
Emp searchKey = new Emp(201,"John",40000);
int index = Collections.binarySearch(empList, searchKey, new EmpComp());
System.out.println("Index of the searched key: "+index);
}
}
class EmpComp implements Comparator<Emp>{
Collections.checkedCollection() method returns a dynamically typesafe view of the specified collection. Any attempt to insert an element of the
wrong type will result in an immediate ClassCastException. Assuming a collection contains no incorrectly typed elements prior to the time a
dynamically typesafe view is generated, and that all subsequent access to the collection takes place through the view, it is guaranteed that the
collection cannot contain an incorrectly typed element.
Write an example for Collections.checkedList() method.
Collections.checkedList() method returns a dynamically typesafe view of the specified list. Any attempt to insert an element of the wrong type will
result in an immediate ClassCastException. Assuming a list contains no incorrectly typed elements prior to the time a dynamically typesafe view is
generated, and that all subsequent access to the list takes place through the view, it is guaranteed that the list cannot contain an incorrectly typed
element.
List chkList = Collections.checkedList(myList, String.class);
System.out.println("Checked list content: "+chkList);
//you can add any type of elements to myList object
myList.add(10);
//you cannot add any type of elements to chkList object, doing so
//throws ClassCastException
How to create empty list using Collections class?
Collections.emptyList() method returns the empty list (immutable). This list is serializable.
How to create empty set using Collections class?
Collections.emptySet() method returns the empty set (immutable). This set is serializable.
How to create empty map using Collections class?
Collections.emptyMap() method returns the empty map (immutable). This map is serializable.
How to Enumeration for ArrayList object?
Below example shows how to get enumeration object for ArrayList object. Collections.enumeration() method provides enumeration object.
How to convert Enumeration to List object?
Collections.list() method returns an array list containing the elements returned by the specified enumeration in the order they are returned by the
enumeration. This method provides interoperability between legacy APIs that return enumerations and new APIs that require collections.
Enumeration<String> enm = vct.elements();
List<String> ll = Collections.list(enm);
Collections.fill() method replaces all of the elements of the specified list with the specified element. This method runs in linear time. You can find the
example code below:
Collections.fill(ll, "TEMP_STRING");
removeCharAt(str, 3))
test_string.codePointBefore(5));
How to determine the upper bound of a two dimensional array ?
This example shows how to search the minimum and maximum element in an array by using Collection.max() and
Collection.min() methods of Collection class int min = (int) Collections.min(Arrays.asList(numbers));
This example shows how to merge two arrays into a single array by the use of list.Addall(array1.asList(array2) method of List class
and Arrays.toString () method of Array class.
list.addAll(Arrays.asList(b));
Object[] c = list.toArray();
This example fill (initialize all the elements of the array in one short) an array by using Array.fill(arrayname,value) method and
Array.fill(arrayname, starting index, ending index, value) method of Java Util class.
Arrays.equals(ary, ary1)
This example initializes enum using a costructor & getPrice() method & display values of enums.
enum Car {
lamborghini(900),tata(2),audi(50),fiat(15),honda(12);
private int price;
Car(int p) { price = p; }
}}
Tower of Hanoi.
= ((n / 2) * (2 * a + (n - 1) * d))
Formula:
E = (P.r.(1+r)n) / ((1+r)n – 1)
Here,
P = loan amount i.e principal amount
R = Interest rate per month
T = Loan time period in year
class LinkedList
{
Node head; // head of list
Insert
Delete
Algorithm For C/C++: Iterate through the linked list and delete all the nodes one by one. Main point here is not to
access next of the current pointer if current pointer is deleted.
In Java, automatic garbage collection happens, so deleting a linked list is easy. We just need to change head to null.
/* Function deletes the entire linked list */
void deleteList()
{
head = null;
}
Recursive –find length
/* Counts the no. of occurrences of a node
(search_for) in a linked list (head)*/
int getCount(struct Node* head)
{
// Base case
if (head == NULL)
return 0;
Traverse linked list using two pointers. Move one pointer by one and other pointer by two. When the fast pointer
reaches end slow pointer will reach middle of the linked list.
/* Function to get the middle of the linked list*/
void printMiddle(struct Node *head)
{
struct Node *slow_ptr = head;
struct Node *fast_ptr = head;
if (head!=NULL)
{
while (fast_ptr != NULL && fast_ptr->next != NULL)
{
fast_ptr = fast_ptr->next->next;
slow_ptr = slow_ptr->next;
}
printf("The middle element is [%d]\n\n", slow_ptr->data);
}
}
n’th node from the end of a Linked List
int count = 0;
if (head != null)
{
while (count < n)
{
if (ref_ptr == null)
{
System.out.println(n+" is greater than the no "+
" of nodes in the list");
return;
}
ref_ptr = ref_ptr.next;
count++;
}
while (ref_ptr != null)
{
main_ptr = main_ptr.next;
ref_ptr = ref_ptr.next;
}
System.out.println("Node no. "+n+" from last is "+
main_ptr.data);
}
}
Reverse a linked list
{
if(head == NULL)
return;
rev(head->next);
Method 1
The idea is to get pointer to the last node of list. And then traverse the list starting from the head node and move the
odd valued nodes from their current position to end of the list.
First detect loop then stop fast pointer and count length btw slow and fast pointer
Sort then compare value to next node value and remove next node if value are same.
Merge two sorted linked lists such that merged list is in reverse order
arr[i]=sc.nextInt();
}
Level order:-
Consider two points with coordinates as (x1, y1) and (x2, y2) respectively.
The euclidean distance between these two points will be
√{(x2-x1)2 + (y2-y1)2}
Left view