Sunday, October 19, 2014

JAVA: charset intro: new String(byte[] bytes, String charsetname)

 

http://stackoverflow.com/a/7048780

Wikipedia explains both reasonably well: UTF-8 vs Latin-1 (ISO-8859-1). Former is a variable-length encoding, latter single-byte fixed length encoding.

Latin-1 encodes just the first 256 code points of the Unicode character set, UTF-8 can be used to encode all code points.

At physical encoding level, only codepoints 0 - 127 get encoded identically; code points 128 - 255 differ by

- becoming 2-byte sequence with UTF-8

- are single bytes with Latin-1.

Wednesday, September 24, 2014

JAVA: Be careful with String class – Performance and Memory

 

1. Operation such as

- String.split()

- String.substring()

uses offset values but keep the ORIGINAL char[] value. Therefore, if you only ever want a portion of the String it will WASTE memory space by storing the original string value

http://stackoverflow.com/questions/7629208/substrings-and-garbage-in-java-1-6

2.  For String.substring()

to get just the portion of the substring, recommend to use

String sub = new String(str.substring(6,12));

http://stackoverflow.com/questions/1281549/memory-leak-traps-in-the-java-standard-api/1281569#1281569


3. General String related:


http://www.javamex.com/tutorials/memory/string_memory_usage.shtml

JAVA: Be careful with String class - General

 

1. JAVA only puts primitive and reference variable onto Stack while all objects, including String, is created and stays on the Heap, subject to GC

http://programmers.stackexchange.com/questions/65281/stack-and-heap-memory-in-java/65289#65289

 

2. String literal value assignment such as

String str1 = “abcd”;

and String variable assignment such as

String str2 = str1

will create these new String objects (which are reference objects) and both str1 and str2 will point to the same object with value “abcd” in the JVM’s internal String Pool

 

3. String Value Object itself, not the reference that points to it, is IMMUTABLE (i.e.the String Class itself is ‘final’), meaning the whenever you try to

String str = someOpToModify(str);

What happens is that another String Value Object is created on the String Pool and this ‘str’ String Reference Object is not changed to point at this new String Value Object rather than the old String Value Object that contains the old value before modification.

http://stackoverflow.com/questions/8798403/string-is-immutable-what-exactly-is-the-meaning/17942294#17942294

 

4. Only way to make sure a new Object of String is created in the String Pool is to call: String str3 = new String(“abcd”);

5. Why to make the String immutable?

http://stackoverflow.com/questions/2068804/why-is-string-final-in-java/2069014#2069014

  1. Security: the system can hand out sensitive bits of read-only information without worrying that they will be altered
  2. Performance: immutable data is very useful in making things thread-safe.

 

 

All and all, be very careful with String in JAVA, especially when it comes to performance and if you have a lot of long Strings to load into the memory:

http://www.javamex.com/tutorials/memory/string_saving_memory.shtml

Sunday, June 1, 2014

JAVA: default values of primitive arrays are Zeros

 

http://stackoverflow.com/a/2154340

 

http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5

 

  • Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):

    • For type byte, the default value is zero, that is, the value of (byte)0.

    • For type short, the default value is zero, that is, the value of (short)0.

    • For type int, the default value is zero, that is, 0.

    • For type long, the default value is zero, that is, 0L.

    • For type float, the default value is positive zero, that is, 0.0f.

    • For type double, the default value is positive zero, that is, 0.0d.

    • For type char, the default value is the null character, that is, '\u0000'.

    • For type boolean, the default value is false.

    • For all reference types (§4.3), the default value is null.

Sunday, May 4, 2014

JAVA: the good old myth of passing by ‘references’

 

http://stackoverflow.com/questions/5607773/change-a-functions-arguments-values

To clarify, the bool variable does not change in the calling method. A new copy of the variable is created in the called method. You can change it as much as u like, but this var is different from the one in calling method. Yet, if your argument was a pointer, then any changes in the called method will directly affect the object in the calling method, since a new copy of the variable is not created in the called method.

http://stackoverflow.com/a/16513496

Java functions parameters are called by reference name, meaning that when you place an object as an function argument, the JVM copies the reference's value to a new variable, and passes it to the function as an argument. If you change the contents of the object, then the original object will change, but if you change the actual value of the reference, then these changes will be destroyed when the function ends.

Therefore, the following call to the sub function will not result a list with appropriate items deleted:

 

    public static void test2() {
MySingleLinkedNode<Integer> list1 = createIntList(new int[]{1,1,1,3,4,6,6,7,7});
MySingleLinkedListUtils.deleteAllFromList(list1, 1);
list1.printRestOfList();




}


 

    public static <T> void deleteAllFromList(MySingleLinkedNode<T> head, T data){
while (head.getNext() != null){
// 1. head is the one we are deleting, loop until we delete all such occurrence
if (head.getData().equals(data)){
head = head.getNext();
}
else{
break;
}
}

// 2. head is not the one we are deleting
MySingleLinkedNode<T> prevNode = head;
while (prevNode.getNext() != null){
MySingleLinkedNode<T> currNode = prevNode.getNext();
if (currNode.getData().equals(data)){
// we found the node to delete
prevNode.setNext(currNode.getNext());
}
prevNode = prevNode.getNext();
}
}

Sunday, April 13, 2014

JAVA: Immutable String… wait for it … reference

 

Simply said, String itself is a ‘reference obj’ not a ‘data obj’

String s1 = "Mississippi";
String s2 = s1;
s1 = s1.replace('i', '!');
System.out.println(s1); // Prints "M!ss!ss!pp!"
System.out.println(s2); // Prints "Mississippi"

Tuesday, November 5, 2013

java: toArray() throws ClassCastException

 

 

The following code (run in android) always gives me a ClassCastException in the 3rd line:

final String[] v1 = i18nCategory.translation.get(id);
final ArrayList<String> v2 = new ArrayList<String>(Arrays.asList(v1));
String[] v3 = (String[])v2.toArray();

 


This is because when you use

 toArray() 

it returns an Object[], which can't be cast to a String[] (even tho the contents are Strings) This is because the toArray method only gets a

List 

and not

List<String>

as generics are a source code only thing, and not available at runtime and so it can't determine what type of array to create.

use

toArray(new String[v2.size()]);

which allocates the right kind of array (String[] and of the right size)

Wednesday, October 9, 2013

Java: generic static method

 

http://stackoverflow.com/a/4409139

You need to move type parameter to the method level to indicate that you have a generic method rather than generic class:

e.g.

static <E> void swapInList(List<E> listToSort, int idxOne, int idxTwo) 
{
    E tmpEle = listToSort.get(idxOne);
    listToSort.set(idxOne, listToSort.get(idxTwo));
    listToSort.set(idxTwo, tmpEle);        
}

Friday, October 4, 2013

Algorithm: need the Grey (or ‘Visiting’) node in DFS?

 

In short, the answer is No. But when we ‘traverse’ to a grey (visiting) node, we can immediately deduce that there is a circle there, simply because we know that in this round of traversal, we started at (i.e. still ‘visiting’) the grey node.

http://cs.stackexchange.com/a/9681 

When doing a DFS, any node is in one of three states - before being visited, during recursively visiting its descendants, and after all its descendants have been visited (returning to its parent, i.e., wrap-up phase). The three colors correspond to each of the three states. One of the reasons for mentioning colors and time of visit and return is to explicitly make these distinctions for better understanding.

Of course, there are actual uses of these colors. Consider a directed graph G. Suppose you want to check G for the existence of cycles. In an undirected graph, if the node under consideration has a black or grey neighbor, it indicates a cycle (and the DFS does not visit it as you mention). However, in case of a directed graph, a black neighbor does not mean a cycle. For example, consider a graph with 3 vertices - A,B, and C, with directed edges as A→B, B→C, A→C. Suppose the DFS starts at A, then visits B, then C. When it has returned to A, it then checks that C has already been visited and is black. But there is no cycle in the graph.

In a directed graph, a cycle is present if and only if a node is seen again before all its descendants have been visited. In other words, if a node has a neighbor which is grey, then there is a cycle (and not when the neighbor is black). A grey node means we are currently exploring its descendants - and if one such descendant has an edge to this grey node, then there is a cycle. So, for cycle detection in directed graphs, you need to have 3 colors. There could be other examples too, but you should get the idea.

Wednesday, October 2, 2013

c/c++: the good old returning local variable

 

http://stackoverflow.com/questions/423186/since-i-cant-return-a-local-variable-whats-the-best-way-to-return-a-string-fr

From what I've seen, this should work as expected:

void greet(){
char c[] = "Hello";
greetWith(c);
return;
}

but this will cause undefined behavior:

char *greet(){ 
char c[] = "Hello";
return c;
}
 
 

You're absolutely right. Your c array in the second example is being allocated on the stack, and thus the memory will get reused immediately following. In particular, if you had code like

 printf("%s\n",greet());

you'd get weird results, because the call to printf would have reused some of the space of your array.

The solution is to allocate the memory somewhere else. For expample:

char c[] = "Hello";

char * greet() {
return c;
}

Would work. Another choice would be to allocate it statically in scope:

char * greet() {
static char c[] = "Hello";
return c;
}

because static memory is allocated separately from the stack in data space.

Your third choice is to allocate it on the heap via malloc:

char * greet() {
char * c = (char *) malloc(strlen("Hello")+1); /* +1 for the null */
strcpy(c, "Hello");
return c;
}

but now you have to make sure that memory is freed somehow, or else you have a memory leak.

Tuesday, October 1, 2013

Java: Can’t create generic array of type T

 

http://stackoverflow.com/questions/2927391/whats-the-reason-i-cant-create-generic-array-types-in-java
 
private T[] elements = new T[initialCapacity];

 


 


It's because Java's arrays (unlike generics) contain, at runtime, information about its component type. So you must know the component type when you create the array. Since you don't know what T is at runtime, you can't create the array.

Java:The meaning of T extends Comparable<T>

 

Review this:

http://stackoverflow.com/questions/8537500/java-the-meaning-of-t-extends-comparablet

 

This means that the type parameter must support comparison with other instances of its own type, via the Comparable interface.

An example of such a class is provided in the Oracle tutorial Object Ordering.

Friday, September 20, 2013

JAVA: Static Nested Class and Normal Nested Class (Inner Class) example code

 

   1: package general_threadCreation;
   2:  
   3: public class CreateThread_RunnableTest 
   4: {    
   5:     // Static Nested Class
   6:     public static class MyRunnableStatic implements Runnable
   7:     {
   8:         private int runnableIdx = -1;
   9:         
  10:         public MyRunnableStatic(int p_runnableIdx)
  11:         {
  12:             this.runnableIdx = p_runnableIdx;
  13:         }
  14:  
  15:         @Override
  16:         public void run() 
  17:         {
  18:             int i = 0; 
  19:             while(true)
  20:             {
  21:                 System.out.println("Static Runnable " + this.runnableIdx + ": " + i);
  22:                 i++;
  23:             }
  24:         }        
  25:     }
  26:     
  27:     // Nested Class (Inner Class)
  28:     public class MyRunnableInner implements Runnable
  29:     {
  30:         private int runnableIdx = -1;
  31:         
  32:         public MyRunnableInner(int p_runnableIdx)
  33:         {
  34:             this.runnableIdx = p_runnableIdx;
  35:         }
  36:  
  37:         @Override
  38:         public void run() 
  39:         {
  40:             int i = 0; 
  41:             while(true)
  42:             {
  43:                 System.out.println("Inner Runnable " + this.runnableIdx + ": " + i);
  44:                 i++;
  45:             }
  46:         }        
  47:     }
  48:     
  49:     
  50:     public static void main(String[] args)
  51:     {        
  52:         // ---- Use the normal nested class (inner class)
  53:         CreateThread_RunnableTest.MyRunnableInner myRunnableInner 
  54:             = new CreateThread_RunnableTest().new MyRunnableInner(1);
  55:         //myRunnableInner.run(); // Not parallel if not putting it into a thread
  56:         Thread myRunnableInnerThread = new Thread(myRunnableInner);
  57:         myRunnableInnerThread.start();
  58:         
  59:         // ---- Use the static nested class
  60:         MyRunnableStatic myRunnableStatic = new MyRunnableStatic(2);
  61:         //myRunnableStatic.run(); //Not parallel if not putting it into a thread
  62:         Thread myRunnableStaticThread = new Thread(myRunnableStatic);
  63:         myRunnableStaticThread.start();
  64:     }
  65:  
  66: }
  67:  

Tuesday, September 17, 2013

Inherit from a class with generic to a class without

 

I can’t believe I didn’t remember this

 

This is no good:

public class MyIntegerTreeNode<Integer> extends MyComparableTreeNode<T>

 

This is good:

public class MyPopulatedIntegerTreeNode extends MyComparableTreeNode<Integer>

Sunday, September 8, 2013

java: Arrays.copyOfRange ‘to’ is EXCLUSIVE

 

java.util.Arrays.copyOfRange(Integer[] original, int from, int to)

 

 

original - the array from which a range is to be copied
from - the initial index of the range to be copied, inclusive
to - the final index of the range to be copied, exclusive. (This index may lie outside the array.)

Thursday, August 15, 2013

c++ managed and unmanaged new

 

Hashtable^ tempHash = gcnew Hashtable(iterators_);

IDictionaryEnumerator^ enumerator = tempHash->GetEnumerator();

 


http://stackoverflow.com/a/202464/2041023


gcnew is for .NET reference objects; objects created with gcnew are automatically garbage-collected; it is important to use gcnew with CLR types


 


http://stackoverflow.com/a/202473/2041023


This is C++/CLI and the caret is the managed equivalent of a * (pointer) which in C++/CLI terminology is called a 'handle' to a 'reference type' (since you can still have unmanaged pointers).

(Thanks to Aardvark for pointing out the better terminology.)

http://stackoverflow.com/a/14378351/2041023

// here normal pointer
P* ptr = new P; // usual pointer allocated on heap
P& nat = *ptr; // object on heap bind to native object
//.. here CLI managed
MO^ mngd = gcnew MO; // allocate on CLI heap
MO% rr = *mngd; // object on CLI heap reference to gc-lvalue

//In general, the punctuator % is to ^ as the punctuator & is to *. In C++ the unary & operator is in C++/CLI the unary % operator. While &ptr yields a P*, %mngd yields at MO^.

c++ cli v.s. clr

 

http://stackoverflow.com/a/480755/2041023

 

The CLR is Microsoft's implementation of the CLI standard.

Sunday, July 21, 2013

java pass-by-value v.s. pass-by-reference

 

package cci_chap1_arrayString;

public class RemoveDuplicate {
    String removeDuplicate(String p_str)
    {
        int len = p_str.length();
        for (int i=0; i<len; i++)
        {
            for (int j=i+1; j<len; j++)
            {
                if (p_str.charAt(j)==p_str.charAt(i))
                {
                    p_str = ((new StringBuilder(p_str)).deleteCharAt(j)).toString();
                    j--;
                    len--;
                }
            }
        }
        return p_str;
    }
    public static void main(String[] args)
    {
        String str = "abbbecettt";
        RemoveDuplicate rdObj = new RemoveDuplicate();
        String resString = rdObj.removeDuplicate(str);
        System.out.println(resString);
    }

}

http://stackoverflow.com/a/8528764/2041023

 

When passing an Object variable to a function in java, it is passed by reference. If you assign a new value to the object in the function, then you overwrite the passed in reference without modifying the value seen by any calling code which still holds the original reference.

However, if you do the following then the value will be updated:

public class StringRef
{
public String someString;
}

static void f(StringRef s)
{
s.someString = "x";
}

public static void main(String[] args)
{
StringRef ref = new StringRef;
ref.someString = s;
f(ref);
// someString will be "x" here.
}

http://stackoverflow.com/a/40523/2041023

Monday, June 10, 2013

64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows

 

 

http://stackoverflow.com/a/950011/2461653

 

This article explains a bit:

"Windows x64 has a directory System32 that contains 64-bit DLLs (sic!). Thus native processes with a bitness of 64 find “their” DLLs where they expect them: in the System32 folder. A second directory, SysWOW64, contains the 32-bit DLLs. The file system redirector does the magic of hiding the real System32 directory for 32-bit processes and showing SysWOW64 under the name of System32."

Edit: If you're talking about an installer, you should really not hard-code the path to the system folder. Instead, let Windows take care of it for you based on whether or not your installer is running on the emulation layer.

Thursday, June 6, 2013

x86, amd64, ia64, EM64T

 

http://blogs.msdn.com/b/heaths/archive/2005/02/17/x86-and-ia64-and-x64-oh-my.aspx

So what is difference between x86, AMD64, IA64, and x64?

- x86 is what most everyone is running now - 32-bit processes on 32-bit Windows.

- AMD64 is Advanced Micro Devices, Inc.'s answer to 64-bit computing that runs 32-bit code natively as well. This means that you can install 32-bit Windows on an AMD64 machine. These machines have already begun shipping with 32-bit Windows XP and a friend of mine in MN is already running one happily.

- IA64 - or Intel Itanium - processors run 64-bit natively and offer 32-bit emulation, but you cannot install 32-bit Windows on it. You need to run Windows Server 2003 for 64-bit Itanium-based Systems.

- Intel has also introduced EM64T - or Extended Memory 64 Technology - for Intel Xeon processors. This processor also supports running 32-bit processes natively like the AMD64.