Friday, December 12, 2014

Generics in Java

Generics:

Type Safety Objects: Allow one type of object, does not allow other object

No Casting required.

For example in Collection

List<String> list = new ArrayList<String>
Allow only string objects to List.

Map<String,Integer> map = new TreeMap<String,Integer>
Allow String and Integer to Map.


When we try to add number it will throw compile time.

General Generic Example

class Generic<T>{
T object;

void add(T object)
{
              this.object=object;
        }

T get()
{
            return object;
        }
public static void main(String[] args) {
     Generic<Integer> ingen = new Generic<Integer>();
     Generic<String> strgen = new Generic<String>();
 
     ingen.add(new Integer(11));
     strgen.add(new String("Generic"));

     System.out.printf("Integer =%d", ingen.get());
     System.out.printf("String =%s", strgen.get());
  }

}

Print Integer =11  String =Generic.

Thursday, December 11, 2014

How to find min Stack using min time

Number of Stacks: 2

Push: Push the items in S1 and Push the item to S2 if the item (top) is less than S1

Pop: Pop the item from S2 because its min value and compare with S1, if both are same then pop item from S1 also.

Popped item is min