Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Thursday, July 19, 2018

List, Set, Map Differences

  1. List: The List interface is a subtype of the Collection interface. It represents an ordered list of objects, meaning you can access the elements of a List in a specific order, and by an index too. You can also add the same element more than once to a List.
    Vector is similar with ArrayList, but it is synchronized.
  2. Set: A Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction. The Set interface contains only methods inherited from Collection and adds the restriction that duplicate elements are prohibited. Set also adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ. Two Set instances are equal if they contain the same elements.
  3. Map: A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. It models the mathematical function abstraction. The Map interface includes methods for basic operations (such as put, get, remove, containsKey, containsValue, size, and empty), bulk operations (such as putAll and clear), and collection views (such as keySet, entrySet, and values).
For more detail check below:


Wednesday, October 15, 2014

Find first non repeated character from string.

There are certain methods finding non repeated character from given string.

1. Using array : Compare each character of string to other character and finding out solution.

private static Character getNon(String string) {
// TODO by character
char[] array = string.toLowerCase().toCharArray();
for (int i = 0; i < array.length; i++) {
boolean isMatch = false;
for (int j = i+1; j < array.length; j++) {
if(array[i] == array[j]){
isMatch= true;
}
}
if(!isMatch){
return array[i];
}
}
return null;
}


2. Using collection : This is second method using collection framework. In this we store char and int pair. Initially non repeated char at 1 if character repeats then index increase by 1. Just get back character from start which contains int value 1.

private static Character getNonCollection(String string) {
// TODO by collection
string = string.toLowerCase();
int iLength = string.length();
Character character;

HashMap<Character, Integer> hashMapChars = new HashMap<Character, Integer>();

for (int i = 0; i < iLength; i++) {
character = string.charAt(i);
if(hashMapChars.containsKey(character)){
hashMapChars.put(character, hashMapChars.get(character) + 1);
}else{
hashMapChars.put(character, 1);
}
}

for (int i = 0; i < iLength; i++) {
character = string.charAt(i);
if(hashMapChars.get(character) == 1){
return character;
}
}
return null;
}

Wednesday, July 17, 2013

String Reverse with n/2 Complexity

The n/2 complexity meaning time require to produce desired output is half . Consider example where we use string reverse , in that case we require to iterate loop over string for each and every element e.g  for i = 0 to i = string.length(). Here in n/2 the loop is half i.e for i = 0 to i = string.length()/2.

Following example shows how to do this !

package string_reverse;

import java.util.Scanner;

public class StrRev {

    public static void main(String[] args) {
        System.out.print("Enter String:");
        Scanner scanner = new Scanner(System.in);
        String enteredStr = scanner.nextLine();

        String reversedStr = stringReverse(enteredStr);
        System.out.println(reversedStr);
    }

    private static String stringReverse(String enteredStr) {
        char temp;
        char[] strRev = enteredStr.toCharArray();
        int len = enteredStr.length();

        for(int i=0;i < len/2;i++){
            temp = strRev[i];
            strRev[i] = strRev[len-i-1];
            strRev[len-i-1] = temp;
        }
        return new String(strRev);
    }
}

The logic behind is to swap first and last element with one iteration and so on . One time you dealing swapping with two character and finally you will get result in n/2 iteration.

Monday, February 4, 2013

Implicitly using the default locale is a common source of bugs

Locale represents a language/country/variant combination. Locales are used to alter the presentation of information such as numbers or dates to suit the conventions in the region they describe.

When you call toLowerCase(), internally toLowerCase(Locale.getDefault()) is getting called.

Calling str.toLowerCase() str.UpperCase without specifying explicit local is common sourse of bug. The reason is that those method uses the current locale of that device ex in Turkish uppercase replacement of "i" is not "I".

You can set locale by using:

Locale.setDefault(new Locale("US"));

You can get locale by using:

Locale loc = Locale.getDefault();

Now you can use custom/default locale:

String class toLowerCase(Locale locale) method example. This example shows you how to use toLowerCase(Locale locale)method.This method Converts all of the characters in this String to lower case using the rules of the given Locale. 

import java.util.Locale;

public class UpperLowerCase
{
    public static void main(String[] args)
    {
        String str = "String to Upper or lower Based on Locale";

        // Get user's default locale
        Locale loc = Locale.getDefault();
        // Convert to lower case
        String s1 = str.toLowerCase(loc);
        // Convert to Upper case
        String s2 = str.toUpperCase(loc);

        System.out.println("old = " + str);
        System.out.println("lowercase = " + s1);
        System.out.println("uppercase= " + s2);
    }
}