Wednesday, December 30, 2009

string manipulation in java part 1: reverse a string

In these series, I'll try to provide code fragments for daily problems in string manipulation. First, we will see how to reverse a string. Note that there are -naturally- more than one way to do this.


public class StringUtils {
public static String reverseString(String string){
/*
Check if the string is not null and empty
*/

if(string != null && !string.isEmpty()){

/*
Create a StringBuilder from the string in hand
*/

StringBuilder str = new StringBuilder(string);

/*
Reverse the StringBuilder content and return it as a String
*/

return str.reverse().toString();
}
return null;
}

public static void main(String[] args){
System.out.println(StringUtils.reverseString("I am your father"));
}
}



Output is "rehtaf ruoy ma I".
It is possible to use StringBuffer instead of StringBuilder. As I don't need thread safety I'll pick StringBuilder which's faster. Quite easy to reverse a string, right?

Tuesday, December 29, 2009

listen to free music online

I talked about justhearit which's a music streaming service. Grooveshark is a great alternative to justhearit. The design of the website and the music archive are awesome. Check it!

Monday, December 28, 2009

change your status in multiple social networks

You can change your status in multiple social networking websites (facebook, myspace, twitter, plurk, linkedin, tumblr, hi5, plaxo ) using quub. Quite practical for those who actively use multiple networking websites.

Wednesday, December 23, 2009

the worst job ever

Chris Hardin shares his bad experiences on his last job as a Senior Software Architect. Take a look here and see if there are similar problems you experience.

Thursday, December 17, 2009

mockito tutorial

Mockito makes life easier for anyone who's writing unit tests. First I planned writing a brief tutorial for Mockito but then I saw Brett L. Schuchert's mockito tutorial. It is as detailed and clear as it can be. I recommend it.

Sunday, December 13, 2009

le roi est mort, vive le roi!

Boxtorrents which was a great torrent tracker for animé changed its name (and domain). You can find it as BakaBT. Vive le nouveau roi!

Sunday, October 25, 2009

no operator overloading in java? tell it to + operator

Lets begin with the wikipedia definition of operator overloading.

In computer programming, operator overloading (less commonly known as operator ad-hoc polymorphism) is a specific case of polymorphism in which some or all of operators like +, =, or == have different implementations depending on the types of their arguments.



It's generally thought that Java does not support operator overloading which is not true.
Take a look at + operator.



int two = 2;
int six = 6;

int sum = two + six;

System.out.println(sum); // output is 8



Quite expected right? I give two operands (two and six) and + operator adds them together. What if I use strings as operands?


String a = "avenged";
String b = "sevenfold";

String result = a + b;

System.out.println(result); // output: avengedsevenfold


+ operator concatenates two strings. As you can easily see + operator has different implementations depending on the type of operands.
Now, lets take a look at some gotchas of the + operator.
What if I mix different types of operands?


int two = 2;
int six = 6;

String str = "depechemode";

System.out.println(two + six + str);

System.out.println(two + str + six);

System.out.println(str + two + six);


The outputs are quite interesting. Let me explain you how it's processed. From left to right it's inspected if there are any strings as operands. As long as I don't see a string I treat + as addition but when I see one I begin to treat every subsequent operand as strings and I concatenate them.

So I have two + six which are two integers. I add them together which makes 8. Then I see a string and treat 8 as a string and concatenate it with str which in result gives "8depechemode".

Later I have two + str. str is a String so two will be treated like one. As I saw a string I treat all of the rest as strings and concat them. The result is "2depechemode6".

For the last example, we see a string as the first operand. We will begin treating every operand as strings and concat them so I'll have "depechemode26" as result.

I hope that everything is clear for + operator and its overloading capabilities.

Saturday, October 10, 2009

refactoring my code (with a little help from my friend Eclipse)

In this post, I'll explain few refactoring tricks and we will use the help of Eclipse as much as possible. Here we go!



Map<String, List<String>> personalItemsMap = new HashMapMap<String, List<String>>();

// for darth vader

List<string> vaderList = new ArrayList<string>();
vaderList.add("lightsaber");
vaderList.add("helmet");
vaderList.add("armor");
personalItemsMap.put("darth vader", vaderList);

// for han solo
List<string> soloList = new ArrayList<string>();
soloList.add("blaster");
soloList.add("vest");
personalItemsMap.put("han solo", soloList);

// for boba fett
List<string> bobaList = new ArrayList<string>();
bobaList.add("blaster");
bobaList.add("mandalorian armor");
personalItemsMap.put("boba fett", bobaList);

System.out.println(personalItemsMap);







Above we create a list of items for each character and add them to an owner-item map. This piece of code is begging for refactoring.



First, I choose the piece of code I'd like to extract as a method.



Then I choose refactor>extract method.


I enter "generateVaderList" as method name and here's our refactored code.


public static void main(String[] args) {
Map<String, List<String>> personalItemsMap = new HashMap()<String, List<String>>;

// for darth vader
List<string> vaderList = createVaderList();
personalItemsMap.put("darth vader", vaderList);

// for han solo
List<string> soloList = new ArrayList<string>();
soloList.add("blaster");
soloList.add("vest");
personalItemsMap.put("han solo", soloList);

// for boba fett
List<string> bobaList = new ArrayList<string>();
bobaList.add("blaster");
bobaList.add("mandalorian armor");
personalItemsMap.put("boba fett", bobaList);

System.out.println(personalItemsMap);
}

private static List createVaderList() {
List vaderList = new ArrayList();
vaderList.add("lightsaber");
vaderList.add("helmet");
vaderList.add("armor");
return vaderList;
}


No need for a temporary reference assignment so I can edit the below part;


List<string> vaderList = createVaderList();
personalItemsMap.put("darth vader", vaderList);


to


personalItemsMap.put("darth vader", createVaderList());


If I do this refactoring for every character my code will be clearer. But think about it. If I do that I'll have three different methods with similar functionality. These methods create a list, add necessary elements to the list and return the list. What if I take these methods and write a more generic one instead of three methods with similar functionality? Later, if I'd like to add a new character I won't write a createNewCharacterList method. I'll use the generic one instead.

Lets see how we can make the method more generic. It creates a list and adds hard-coded strings to it. This method will be general if I hand it the item strings to add. First I choose the name of "createVaderList" and then right click. Then refactor>rename. I rename it as "createItemList". I'm writing a more general method, remember? I can change the method signature from the menu but this is not so handy so I'll skip that and edit my method by hand.


private static List createItemList() {
List<string> vaderList = new ArrayList<string>();
vaderList.add("lightsaber");
vaderList.add("helmet");
vaderList.add("armor");
return vaderList;
}


will become


private static List<string> createItemList(String... items) {
List<string> itemList = new ArrayList<string>();

for(String item : items)
itemList.add(item);

return itemList;
}


In this new method, we -again- create a list. Then we take an arbitrary number of strings. I assure this behavior by using var-args. Then in our beautiful for-loop we add the items to the item list and return the list.

After that we will do the necessary changes in the code. Eclipse can't help us in this case. After we do the necessary changes in our code, our main method will be such as below;


public static void main(String[] args) {
Map<String, List<String>> personalItemsMap = new HashMapMap<String, List<String>>();

// for darth vader
personalItemsMap.put("darth vader", createItemList("lightsaber", "helmet", "armor"));

// for han solo
personalItemsMap.put("han solo", createItemList("blaster", "vest"));

// for boba fett
personalItemsMap.put("boba fett", createItemList("blaster", "mandalorian armor"));

System.out.println(personalItemsMap);
}


Much clearer and more usable right?

Sunday, October 4, 2009

new metal gear peace walker trailer

Check the new metal gear solid: peace walker trailer from the Tokyo Game Show 2009.
The plot is confusing even for the fans of the series, but we eagerly wait for the magnificient work that'll be delivered by Hideo Kojima.

Friday, September 18, 2009

google collections api

Every developer that works with Java collections for some time will realize the limitations of Java's Collections API. It looks like Google developers share the same opinion which results in the development of their own API. Benjamin Winterberg has a good blog entry about the said API.

Tuesday, September 15, 2009

twitter

I got my twitter account. Tweet me!

Friday, August 14, 2009

eclipse magic part 2: correct indentation automatically

Eclipse tries to offer a correct indentation while you're writing your code, but there are times it does not work well. In result, you got a less readable code. Either you have to correct its indentation by hand or you have to use the eclipse magic.

 
for(Float number : numberList)
System.out.println(number); // need an indentationhere

Collections.sort(numberList, new FloatComparator());
System.out.println("------- after sorting takes place -----");

for(Float number : numberList) // need indentation for the
//two following lines
System.out.println(number);



Now choose the lines you want to the indentation (or the whole text) and either do CTRL + I or Source > Correct Indentation. Here's the result:

 
for(Float number : numberList)
System.out.println(number);

Collections.sort(numberList, new FloatComparator());
System.out.println("------- after sorting takes place -----");

for(Float number : numberList)
System.out.println(number);

Wednesday, August 12, 2009

method overloading in java (with umberto tozzi)

Method overloading allows you to use the same method name with different arguments. As long as the "different arguments" constraint holds, you are free to change the return type, the access modifier and the thrown exception of the method. Lets see it on an example.


private void sings(String lyrics){
System.out.println("Tozzi sings these lyrics: "+lyrics);
}

public void sings(int times){
System.out.println("Tozzi sings "+times+" times");
}



I'm free to change the access modifier private to public of the overloaded method as long as I use another argument type in the method.



private void sings(String lyrics){
System.out.println("Tozzi sings these lyrics: "+lyrics);
}

String sings(int times){
String message = "Tozzi sings "+times+" times";
System.out.println(message);
return message;
}


Above I change the access modifier (from private to package access) and the return type (from none to String).


private void sings(String lyrics){
System.out.println("Tozzi sings these lyrics: "+lyrics);
}

private void sings(boolean isUmbertoSick) throws Exception{
if(isUmbertoSick)
throw new Exception("Umberto Tozzi is sick");

System.out.println("Tozzi sings 'Ti amo'");
}


Above I added an exception to the overloaded method. The method checks if Umberto Tozzi is sick and throws an exception in this case. If he's ok, Umberto gladly sings his hit single "Ti Amo".

An interesting case is when you overload methods which have two classes with superclass, subclass relationship between (one class inherits the other) as argument. Lets see it in an example.


class Song { }
class Ballad extends Song { }

public class UmbertoTozzi {

private void sings(String lyrics){
System.out.println("Tozzi sings these lyrics: "+lyrics);
}

private void sings(Song song){
System.out.println("Tozzi sings the song "+song);
}

private void sings(Ballad ballad){
System.out.println("Tozzi sings the ballad "+ballad);
}

public static void main(String[] args) {
// create UmbertoTozzi object
UmbertoTozzi tozzi = new UmbertoTozzi();
// create a Ballad and Song object
Ballad ballad = new Ballad();
Song song = new Song();
// give the ballad and song references to
// the sings method
tozzi.sings(ballad); /* output: Tozzi sings the ballad Ballad@a6aeed */
tozzi.sings(song); /* output: Tozzi sings the song Song@126804e */

// bind a Ballad object
//to a Song reference
Song newSong = new Ballad();

tozzi.sings(newSong);
/* output: Tozzi sings the song Ballad@b1b4c3 */
}
}


There are three overloaded methods above. One accepts arguments of type String, the other Song and the last one Ballad. Notice that Ballad extends Song which means that Ballad is a Song. Ballad is the subclass while Song is the superclass. The last output is quite confusing. I sent a Ballad object to the sings method. Why sings(Song song) is called instead of sings(Ballad ballad) ? The answer is quite plain. The object related to the reference is not checked. If we put it in another way, the method call is done in compile time, not in runtime. So the compiler sees that the reference type is Song and it calls the corresponding method.
Long live Umberto Tozzi!

Tuesday, August 11, 2009

Saturday, August 8, 2009

how to sort using comparators

Although Collections class' sort method is quite handy, there will be times you'll need to do tricky stuff while sorting. But you can still use this static method with your Comparator that'll ensure the desired sorting behavior.

Lets quote the definition of Comparator class:
A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order


Assume that we want to sort a List of floats by considering only the part after the dot. So we will consider 63 of 3.63 and 72 of 2.72 and their increasing order will be {3.63, 2.72} because 63 < 72. The code of the Comparator is below.


// we use generics (Float here) for avoiding a downcast
class FloatComparator implements Comparator < Float >{

public int compare(Float f1, Float f2) {
// for instance, 323.432 - 323 ~= 0.432
Float f1_ = f1 - f1.intValue(); /* intValue() returns the floor integer (not the closest integer) */
Float f2_ = f2 - f2.intValue();
/* after stripping the float from the integer part we use float's compareTo function compare the remaining part of the number */
return f1_.compareTo(f2_);
}


}




We implemented the Comparator interface in the class. In public int compare method we first remove the integer part of the float and then compare the rest. If you must do more trickier stuff you have to consider few things. I'm quoting from Sun's Comparator documentation:

The implementor must ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y. (This implies that compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)

The implementor must also ensure that the relation is transitive: ((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.

Finally, the implementor must ensure that compare(x, y)==0 implies that
sgn(compare(x, z))==sgn(compare(y, z)) for all z.



As we use the compareTo method of Float, we don't have to think about the above cases. They are already handled.

Lets see our FloatComparator in action.


public class SortingWithComparator {

public static void main(String[] args) {
List < Float > numberList = new ArrayList < Float > ();
numberList.add(323.432F);
numberList.add(34.234F);
numberList.add(-81.01F);
numberList.add(49.736F);

for(Float number : numberList)
System.out.println(number);

Collections.sort(numberList, new FloatComparator()); /* sort numberList using the FloatComparator */
System.out.println("------- after sorting takes place -----");

for(Float number : numberList)
System.out.println(number);

}
}


The output is:


323.432
34.234
-81.01
49.736
------- after sorting takes place -----
-81.01
34.234
323.432
49.736

Friday, August 7, 2009

eclipse magic part 1: automatically generate getters and setters for your instance variables

Everyone who tried to write a getter / setter (accessor, mutator) method for more than 2-3 fields knows that it's a pain. Eclipse can automatically generate a getter/setter method for the instance variable you choose. Assume that I have a java bean for a student (StudentBean).


public class StudentBean {
private int studentId;
private String name;
private float gpa;
}


If I'm going to write a get/set method for each variable I'll have to write 6 methods in total. Let Eclipse to this job.
 Source > Generate Getters and Setters


Then choose the fields.



You can choose the insertion point of the automatically generated methods, their order and their access modifiers. My new StudentBean is now like this:


public class StudentBean {

private int studentId;
private String name;
private float gpa;

public int getStudentId() {
return studentId;
}

public String getName() {
return name;
}

public float getGpa() {
return gpa;
}

public void setStudentId(int studentId) {
this.studentId = studentId;
}

public void setName(String name) {
this.name = name;
}

public void setGpa(float gpa) {
this.gpa = gpa;
}

}

Wednesday, August 5, 2009

burpee the ultimate workout!

Pretty confident title right? This exercise develops lots of different muscles and does not take too much time. I've been doing burpee for few months and I can't recommend it enough. Take a look at the video below for doing it right.

Saturday, June 27, 2009

transformers: revenge of the fallen f.a.q.

Topless Robot has an hilarious f.a.q. about the second transformers movie. It is just GREAT. Lots of plot holes, inconsistencies are revealed. Take a look at this faq.

constructor tricks: constructor overloading, calling constructor from constructor


Did I catch your attention with the megan fox picture?
I assume that the answer is yes, great.

Constructor overloading is not really different from a method overloading.
In practice, all you have to do is to give different arguments to similar methods.
For a Fruit class,
  Fruit(String name_, int count_) 
and
  Fruit(String name_, int count_, String color_) 
are both constructors. They are similar in almost every way; only difference is that the second one has a color attribute.

Now, let's move to a more tricky subject. Calling a constructor from another constructor. You can ask why would I want to do that. Let's see it on our example:

 public class Fruit {

int count;
String name, color;
final static String SEPARATOR = ", ";
// the part below is where I use constructor overloading
Fruit(String name_, int count_){
name = name_;
count = count_;
}

Fruit(String name_, int count_, String color_){
name = name_;
count = count_;
color = color_;
}
// the part above is where I use constructor overloading

public String toString(){
String returnValue = "name: "+name+SEPARATOR+"count: "+count;
if(color != null)
returnValue += SEPARATOR+"color: "+color;

return returnValue;
}

public static void main(String[] args) {
// create three apples which I dont care the color
Fruit apples = new Fruit("apple", 3);
System.out.println(apples);

// create two yellow melons
Fruit melons = new Fruit("melon", 2, "yellow");
System.out.println(melons);
}

}


As you can see the example is pretty straightforward. This is the fruit class. There are two mandatory and one optional attribute related to my class. Fruit name and fruit count are mandatory and the color is optional. So to have this effect, I used constructor overloading.

Now lets see why would I want to call a constructor from another constructor. As you can see both constructors in the example share the mandatory attributes. So I can easily call the first constructor from the second one (by using this() keyword) and remove the code that has a reoccurence. The below code is improved in readability as you can see.

 public class Fruit {

int count;
String name, color;
final static String SEPARATOR = ", ";

Fruit(String name_, int count_){
name = name_;
count = count_;
}
/*
removed two redundant lines and added "this" to call the constructor above.
we give its essential parameters (name and count) by passing them
to "this" as arguments.
*/

Fruit(String name_, int count_, String color_){
this(name_, count_);
color = color_;
}

public String toString(){
String returnValue = "name: "+name+SEPARATOR+"count: "+count;
if(color != null)
returnValue += SEPARATOR+"color: "+color;

return returnValue;
}

public static void main(String[] args) {
Fruit apple = new Fruit("apple", 3);
System.out.println(apple);

Fruit melon = new Fruit("melon", 2, "yellow");
System.out.println(melon);
}

}

Saturday, June 20, 2009

13 minutes of "god of war III" heaven

God of War I and II are both excellent games which were released on playstation 2 platform. Later, God of War: Chains of Olympus which was again a great game is released on PSP. The subsequent game -God of War III- is probably one of the most anticipated games of playstation 3 platform. You can watch 13 minutes of blood, sweet and tears from God of War III below.



Sunday, June 14, 2009

resizing pictures in batch

You got photos of last night and you want to submit to facebook or send them to your friends. But there's a little problem: the pictures are too big for uploading. You can resize them so they'll take less space and then it'll be less painful to post it somewhere or to send it to some friend of yours. But there's another problem. Will you resize the pictures one by one? What if there are more than a dozen?

Fotosizer is a batch image resizer that will solve your problems. You can choose the new size (while maintaining the aspect ratio if you want) and the output file format (jpg, bmp, gif, tiff, png). Plus fotosizer is a freeware. I highly recommend it.

Wednesday, June 3, 2009

metal gears?

Yeah, metal gears indeed with a big S in the end. There are two metal gear projects. The first one in Metal Gear Solid: Peace Walker where Hideo Kojima -probably because of his claim that he won't participate to future metal gear projects- stresses on his high level of participation to the project. The game will probably be a similar game to Metal Gear Solid: Portable Ops in terms of release medium (PSP) and protagonist (Big Boss).

The second game (Metal Gear Solid: Rising) will have Raiden as hero and although we don't know much about the game it is rumored that the game is a kind of sidestory instead of a real sequel. The game will be released on Xbox 360, Playstation 3 and PC.

It looks like my playstation 3 purchase will have to wait future great games.

Wednesday, May 27, 2009

vncconfig's copy/paste bug

I'm doing my coding on a workstation by connecting to it with a vnc client. To be able to do copy/paste or cut/paste between my computer and the workstation I use vncconfig. But there are times it does not work at all. You copy your text on one computer and when you try to paste it on the other computer, nothing happens. I discovered a workaround for this. Assume that you're trying to copy/paste from computer A to computer B and nothing happens. Open the screen of computer B, copy some text from it (anything). Then open computer A and copy the desired text, later paste it in computer B. It'll do the paste now.

new metal gear? (part 2)

metal gear solid 5
Kojima strikes again! Kojima Production Website contains a teaser of a new metal gear game in which we will probably see Big Boss as the hero. I captured the picture in the right from the teaser.
Game's details like on which platforms it'll be available will be -probably- revealed in E3. If there's going to be a second metal gear on Playstation 3, there'll be no escape for me from buying it (this time).

Thursday, May 21, 2009

fixing inverted controls in x-men origins: wolverine the game

All controls in X-Men Origins: Wolverine game was inverted when I was trying to use my gamepad (which is not an xbox360 gamepad), which means that up was down and right was left. To fix this issue, open your game installation directory. Then open the WGame and then Config folder. After that, edit DefaultInput.ini and find
 Bindings=(Name="XboxTypeS_LeftY",Command="Axis aBaseY Speed=1.0 DeadZone=0.3" 
line and change "1.0" in it to "-1.0" and voila! Your inverse controls problem vanishes.

Wednesday, May 13, 2009

dragonball: evolution is more than 1.5 times better than dragonball: evolution

An average anime fan would know Dragon Ball or Dragon Ball Z which are both works of mangaka Akira Toriyama. Although I'm not a big fan of both series, I can't help myself hating the live action movie project after seeing its trailer. From the look of it, the only likeness between the movie and the animé is the character names.
After the psp game news of the same movie, I begin to think if things can get worst for the franchise. I doubt it very much after seeing the reviews. On Metacritic, the movie has 45/100 while the game has 28/100 as the average rating. Congratulations to Dragon Ball the movie which sucks less than the game which sucks less than probablysomethingexistingthatImnotawareof.

Monday, May 4, 2009

esoteric programming languages

Wikipedia has an awesome article about esoteric programming languages. Only few of them is designed for being adopted for real world problems. But the majority of them are quite interesting and entertaining. Take a look at Brainfuck for instance. You won't meditate much on the naming of this programming language after seeing the Hello World example.


++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++
..+++.>++.<<+++++++++++++++.>.+++.------.--------.>+.>.

Monday, April 27, 2009

recommendation for people with desire to throw money away: burningairlines.com

About half a year ago, I ordered bunch of t-shirts from burningairlines.com. I never got these t-shirts and neither burningairlines, nor usps did care what happened to my order. If you got loads of money to throw away, I highly recommend you to shop from burningairlines; satisfaction guaranteed.

Friday, April 24, 2009

secrets of list class part 2: xAll strikes back

I continue my series of entries about less known features of the List class and today I'm going to explain the uses of addAll(), retainAll(), removeAll() methods.
Assume that you have two Lists and you want to merge them somehow.


/* list1 consists of [1, 2, 3, 4, 5] and list2 consists of [6, 7, 8, 9]*/
/* I want to merge both lists*/
/* I can use addAll and add list2 at the end of list1*/
list1.addAll(list2);
/* if we take a look at list1 we will see*/
System.out.println(list1);
/* output is [1, 2, 3, 4, 5, 6, 7, 8, 9] */


If you take a look at the illustration above you'll see that red, green part of the sets and two blue part of the sets (elements of the intersection are used 2 times each) are obtained after addAll().


If we don't want elements of the second list to be added to the end of the first list then we can use addAll() with an index argument.


/* list1 consists of [1, 2, 3, 4, 5] and list2 consists of [6, 7, 8, 9] (again)*/
/* I want to merge both lists*/
/* but I want that list2's elements come first*/
list1.addAll(0, list2);
System.out.println(list1);
/* output is [6, 7, 8, 9, 1, 2, 3, 4, 5] */


Notice that
 list1.addAll(list2) 
and
 list1.addAll(list1.size(), list2) 
are the same thing and adding the list2 to the list1 does not effect the content of list2.

Now, it's the removeAll()'s turn. You can remove all the elements of a Collection from a List using this method.


/* list1 consists of [1, 2, 3, 4, 5] and list2 consists of [6, 7, 8, 9] (again)*/
/* I want to remove elements of list2 from list1*/
list1.removeAll(list2);
System.out.println(list1);
/* output is [1, 2, 3, 4, 5]. list1 is intact because there are no elements */
/* of list2 in list1*/




/* list1 consists of [1, 2, 3, 4, 5] and list2 consists of [3, 8, 9, 4]*/
/* I want to remove elements of list2 from list1*/
list1.removeAll(list2);
System.out.println(list1);
/* output is [1, 2, 5]. 3 and 4 which are elements of both list1 and list2 */
/* are removed from list1*/



If you look at the picture above you'll see that we took only the red part of list1 and removed the intersection from it.

The last method of my entry will be retainAll(). retainAll() retains only shared elements of list1 and list2.


/* list1 consists of [1, 2, 3, 4, 5] and list2 consists of [3, 8, 9, 4]*/
/* I want to retain only shared elements of both lists */
list1.retainAll(list2);
System.out.println(list1);
/* output is [3, 4] */



If you take a look at the picture above you'll see that we retain only the intersection which is the blue part of list1. That's all for part 2 secrets of List class part 2.

Sunday, April 19, 2009

concurrentmodificationexception or: how I learned to stop worrying and loved for-each loop as it is

Few days ago, I got a ConcurrentModificationException out of nowhere while I was iterating through a list and removing elements from it. I remember doing this thing and not getting any exception. I delved a little bit and realized that the exception is thrown because of my misuse of for-each loop (introduced in jdk 5). Its developers noted:
Consider, for example, the expurgate method. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel.


For-each loop creates and hides the iterator, so when you try to remove an element using the list itself you'll get ConcurrentModificationException because you have to do the removing and adding through the iterator. So the code below will throw ConcurrentModificationException.

/*
integerList is an ArrayList
with Integer objects as elements
*/

for(Integer integer : integerList){
if(integer.intValue()%2 == 0) // remove even elements
integerList.remove(integer);
}


You can fix your error by not using for-each loop. For instance, you can define your iterator and work with it or you can iterate through the array list and do the add/remove directly from the list.

First one's code:


Iterator iterator = integerList.iterator(); // create the iterator
while(iterator.hasNext()){
Integer integer = iterator.next(); // take the element
if(integer.intValue()%2 == 0)
iterator.remove(); // remove using the iterator
}


Second approach's code:



for(int i=0 ; i < integerList.size(); i++){
Integer integer = integerList.get(i); // take the element
if(integer.intValue() %2 == 0){
// remove from the list
integerList.remove(i);
/*
decrease the index by one, so
that we won't skip any elements
after the element left-shifting which
occurs after each removal.
*/

i--;
}
}

Saturday, April 18, 2009

secrets of list class part 1: constructor tricks

List classes in Java can be thought as resizable arrays. They are very frequently used as they are handy. In this part of the article, I'll show you two constructor tricks that can become quite useful in special cases. The first trick is for using an existing list content for creating a new list. The second trick is for ensuring the element capacity of a list. You can ask yourself why are we giving a capacity value to a list if it can increase its capacity by itself. The answer is that yes, lists can increase their capacity by themselves but if we know the potential size we can skip waiting for the initial capacity adjustment and save some precious time. Here's the code for constructor tricks:



/* create two Integer objects which are wrappers for integers */

Integer integer1 = new Integer(1);
Integer integer2 = new Integer(2);

/* create an ArrayList and add both objects to list1*/

List list1 = new ArrayList();
list1.add(integer1);
list1.add(integer2);

// constructor tricks begin

/* to create a new list (list2) with elements of a list (list1)
* give list1 to the constructor of list2 while creating list2
*/

List list2 = new ArrayList(list1);

// you can see that their content are the same

System.out.println(list1);
System.out.println(list2);

/*
* we know that a large number of elements will be added to the list
* so the initial capacity of 10 will not be enough and
* the list will have to expand.
*
* if we have an idea about the potential initial size for a list
* we can ensure that the list's initial capacity will be large
* enough to handle the initial size of elements.
* */

final int potentialSize = 10000;

/* to create a list of desired capacity, give the capacity value
to its constructor */

List list3 = new ArrayList(potentialSize);

// add all elements to list3

for(int i=0 ; i < tmpinteger =" new">

Saturday, April 11, 2009

10 things every programmer should know for their first job

James Stroup has a great article which can be quite useful for programmers who get their first job. I can't recommend it enough.

Thursday, April 2, 2009

bookmarking or launching several websites with a single click

There are lots of open websites and you want to check them later? Or there are several sites you want to open with a single click, so you don't have to open them one by one? Then, here comes maxthon 2's magical solution; using the groups.

Assume that there are several website tabs and you want to save them. You should
  Open groups 

  Click on Add all tabs as group 

  Enter group name 

  Press OK :) 

Next time you want to open all these previous sites, you should
 Open groups 

  Click to the group name 

Tuesday, March 31, 2009

suggested small language changes for jdk 7

Project Coin has the goal of grouping language changes suggested for JDK 7. David Linsin has brief listing of these proposals with code examples to clearify things. I suggest you to take a look.

Monday, March 30, 2009

how to fix sudo command in zenwalk 6

What you wait from sudo command is that it gives you the power of root for a single command. But you'll notice that it does not work properly in Zenwalk 6. To fix it;

check your group by opening your start menu > system > control panel > user profiles > list users > your_username > hit ok > note groupname value

open Terminal

type

su

and login (then you become root)

type

mousepad /etc/sudoers



edit the line after

# Uncomment to allow people in group wheel to run all commands

comment as

%your_groupname_value ALL=(ALL) ALL
and save. Voila.

Sunday, March 29, 2009

Friday, March 27, 2009

remove last login information from zenwalk start-up

I have a new toy called Zenwalk and I'm using auto-login as usual for buying some time. But there's something bothering me with my new toy; in every boot, it shows me my last login's time and date and there's no way to get rid of this thing through zenwalk's settings. For removing this annoyance, you have to follow these steps:

  1. open Terminal
  2. type
    su
    and login

  3. type
    mousepad /etc/pam.d/system-auth 
    and add
    #
    to the beginning of
    session    optional   pam_lastlog.so
    line.
  4. save and quit mousepad

Saturday, March 21, 2009

you wish you could catch and cancel that email you sent, don't you?

If your answer to the title of this entry is yes or YES or several time yes/YES, then rejoice because now gmail can undo emails. After you send an email with google mail, you have five seconds to change your opinion and cancel sending this mail. It is an inarguably useful feature considering how many times you (I) wish you (I) didn't send "that" email. A job application without a CV attached to it is not that effective isn't it? Yeah I though so...

Notice that it's a labs feature. You have to activate it from there to use it.

Thursday, March 19, 2009

netbeans 6.5 and struts 2

It is not really straightforward to add Struts 2 capabilities to Netbeans 6.5, so I'll try to explain it in details.


  1. Go to nbstruts2support project's page and download two nbm files under the "release modules" folder.
  2. Open netbeans 6.5 > tools > plugins > downloaded > add plugins. Then choose both nbm files and click next until the installation is complete.
  3. You can now create java web projects with struts 2 framework support (Don't forget to tick Struts 2 on Frameworks window). Notice that you can automatically generate a "hello world" page using Struts 2.

Wednesday, March 18, 2009

data mining in hr department?

Businessweek has a short article about the usage of data mining in human resources departments. Although the article is -unfortunately- free of statistical details, it's still an interesting read for learning the practical uses of data mining. In this example, data mining is used for assessing "values" to workers for extracting important and less important workers.

ibm is planning to buy sun

Although there's no official statement on the matter, world street journal informs us of the possibility that IBM is planning on buying Sun. I wonder what will happen to Netbeans if that transaction takes place. Even though I largely choose Eclipse over Netbeans, it won't be cool to lose that IDE. I still think that Netbeans is better than Eclipse for web development on Java.

Friday, March 13, 2009

madworld

MadWorld is one of the rare mature games Wii has to offer; a distinctive visual style, a good plot and a game to revive the genre which's dead for years. I wish I had a wii for the first time. Check ign's review:

Saturday, March 7, 2009

music, movie, book recommendations from tastekid

There are lots of sites for recommending music, books or movies based on your tastes. TasteKid is one of them and it offers good recommendations (as far as my tiny number of tests proves). Usually, it returns a high number of recommendations and thus it can fetch several unsimilar results which's its achilles' heel.

TasteKid has an interesting feature. Assuming you choose to search a movie, it can recommend you similar books and music next to similar movies. It can become quite handy sometimes. For instance, I chose "Batman Begins" as my movie query. I was expecting to have "The Dark Knight", Tim Burton's Batman movies and several comic adaptations as result. TasteKid recommended me these in addition to several comic book titles which are well selected in my opinion.

Friday, March 6, 2009

top 16 useful shortcuts in eclipse

Code of Doom presents the most useful Eclipse shortcuts. If you're using Eclipse for sometime you'll know some of them for sure, but there could be some shortcuts you missed. Check it!

Thursday, March 5, 2009

an eclipse summit in istanbul? here comes eclipsist!

In 28, 29 april, an Eclipse summit (Eclipsist) will be held here in Istanbul. Eclipsist will contain some workshops and speeches about subjects pertaining to Eclipse (can't you believe?) and Java EE. The fact that there's no entrance fee to the summit obviously increases its charm.

revolution renaissance shares two songs for free

Stratovarius used to be one of my favorite power metal bands. After the band split up, the lead guitarist/main composer Timo Tolkki left the band for forming a new one named Revolution Renaissance which released a so so debut album. Revolution Renaissance shares two songs from their upcoming album for free (let me note that their website have a problem with Internet Explorer). Fingers crossed for a better second album!

Monday, March 2, 2009

take one line notes easily in linux with touch (of evil)

You're reading some comics or watching some serie and you want to take note of the last book/episode you read/watched so, few days later, you can continue from where you have left. One of the most practical ways of doing that is to put a reminder in the comic/serie directory. No need to create a text file named "tome-11" or "scrubs-s05-e11", you can create an empty file with the desired name in a single second. We can do it by using touch (of evil) command. Usually, touch command is used for changing access and modification time of files but also it is an easy way to create an empty file. Just open the terminal and write
 touch yourNote
in the comic/serie directory.

Saturday, February 28, 2009

find the process id of an application in linux

In one of my previous posts, I talked about killing unresponsive processes in Linux. It is pretty straightforward to find the process ids of applications if you're the only user, but if that's not the case you have to find a clever way. Assume that we want to find the process id of bash. We write
ps -A
to the terminal for seeing all active processes but we don't have 1 hour to inspect all processes. We just want to see the process id of bash. We will use the pgrep command which's basically a grep variant for processes.
pgrep bash
will give us the process id (PID) of bash.

Friday, February 27, 2009

name the node

NASA offers you the chance to name a component (node 3) of a space station and one of the choices is "Serenity". Terrific!

Thursday, February 26, 2009

comic book reader

I use Cdisplay on Windows for reading comic books (in cbr and cbz formats which are basically rar and zip archives containing image files). I searched for a similar application on Linux and found few alternatives. One of the best of these applications is Qcomicbook which can be obtained thru synaptic package manager or by writing "apt-get install qcomicbook" (assuming -of course- your linux distro is debian-based).

italics! everywhere!

Today, I saw that Google's font is in italics and another website's font is in italics and some application's font is in italics; what a lovely coincidence! I had no idea how this happened, but fonts switched to italic mode without asking my opinion. The odd thing's that Firefox doesn't have this problem. For fixing this, I downloaded arial font and installed it. I was planning to download and install all vista fonts, but installing the arial font fixed the problem.

Thursday, February 19, 2009

public tracker list for torrents

Sometimes I bump into torrent files with unreachable trackers (due to the blocking of my ISP) and then either I have to find an alternative tracker for being able to download the file or find an alternative torrent with a reachable tracker. I generally choose the first option and everytime I see a torrent file with unreachable tracker(s), I add several public torrent trackers to its tracker list and most of the time at least one of the trackers contain the torrent file in hand. You can download a public tracker list for torrent files. You should notice that the file formatting is prepared for utorrent.

Tuesday, February 17, 2009

distros with xfce

As I wrote previously, Xfce is the best choice as desktop environment for older PCs. Planete Beranger reviews several distros that comes with Xfce. It's rather thorough. Check this distro review.

Sunday, February 15, 2009

just hear it! listen to any song you want; online, free and legal

Just Hear It! is an awesome website that makes lots of songs available to anybody for listening. Its service is free and all you need is a flash plug-in. Even obscure bands/songs is available for listening and the service is legal (at least the website says so). Give it a try!

Saturday, February 14, 2009

generate your favicon

Favicon Generator offers favicon generation service by either using your image files to generate favicons, or by giving you the chance to design your own favicon with a very simple tool. The whole service is web-based and it works quite good.

Friday, February 13, 2009

igoogle's language switching proglem

I'm using iGoogle because I like the idea of having a personalized homepage with my e-mails, todo list, current weather information and aggregated news from different sources in it. But although I'm using a Windows Vista in English, iGoogle keeps on turning the language to Turkish (probably due to the regional settings of my Windows) and lots of its content are changing (which annoys me very much). So I'll present you the tip to change the language of your iGoogle into English: add "?hl=en" to http://www.google.com/ig and use http://www.google.com/ig?hl=en.

Wednesday, February 11, 2009

crank 2 trailer

Crank 2: High Voltage just continues from where the first one left. Lots of mindless violence, lots of girls, lots of gun fights. Again a movie that does not take itself serious. Chev Chelios rocks!

Tuesday, February 3, 2009

ready to kill some processes/applications in linux?

In Linux -as in all modern Operating Systems-, applications become unresponsive and you may want to kill the process pertaining to them. To do this, open the terminal and write this:

killall applicationName

If that does not work try

killall -9 applicationName

If you don't have an idea about the application name, you can take look at the current processes by writing

ps

then to kill the processes you want

kill processID

If that does not work then try

kill -9 processID

Another possibility is to use xkill (for applications with gui). The window of the application waiting to be killed should be visible. Then, open Terminal and type

 xkill 
and later choose the window of the application to be killed.

Monday, February 2, 2009

better touchpad performance in linux mint

After some time with Linux Mint I realized that I'm not fully satisfied with the behavior of my touchpad and thought about downloading a program which will allow me to tweak it. I downloaded gsynaptics thru synaptic package manager and edited xorg.conf for gsynaptics to work. First you should open xorg.conf with a text editor. There's a text editor called Mousepad that's bundled to Linux Mint. So all you have to do is to open Terminal. Then write "sudo mousepad /etc/X11/xorg.conf" and press enter. Then find the section below:


Section "InputDevice"
Identifier "Synaptics Touchpad"


Add the line
Option     "SHMConfig"     "true"
as the last entry (just before EndSection). Save the conf file and reboot. Later, open the Terminal and write "gsynaptics" and configure your touchpad. Voila!

Sunday, February 1, 2009

new batman game: "batman: arkham asylum"

The trailer of the new batman game "Batman: Arkham Asylum" can be seen below. The voice acting is not bad, and the plot seems ok. I wonder how many hours per day batman spends body building and what amount of steroids does he use. He looks like a goddamn body building champion.



Saturday, January 31, 2009

maybe the most widely used chord sequence ever

Take a look here to see (and listen) one of the most popular chord sequences in songs. Lots of "good" songs use it huh?

Tuesday, January 27, 2009

top ten bizarre lego sets

Topless Robot made a great top ten list for bizarre (and awesome) logo sets. If you were playing legos in 80s, it's sure you'll remember some of these fantastic things. I can't manage to forget Robot Command Center (in the left) for instance. Now, as an engineer, I try to guess the functionalities of these short tentacles in the place of knees, the compartment in the lower side of torso ...etc, but no luck in incorporating these body parts with meaningful tasks.

Tuesday, January 20, 2009

my quest for the greatest linux distro

Well, I can't tell that I found THE linux distro, but I tried Ubuntu and OpenSUSE and their performance can't match with Linux Mint (Xfce) on my three year old laptop. Linux Mint is Ubuntu-based, so we got the advantages of Ubuntu which's Debian-based and it is lightweight thanks to Xfce which is a desktop environment lighter than gnome (should I compare with Kde?). Furthermore, Linux Mint is user-friendly and I think that it is a good distro to start your linux adventure.

Friday, January 16, 2009

read attached pdf without acrobat reader

gmail pdf Thanks to Gmail's new service, it is possible to read PDF files attached to e-mails without the need of saving them and opening them with Acrobat Reader. I tried the new feature and it worked flawless as long as I could test it. As you can see in the picture, all you have to do is to click on "view" to read the PDF file.

super hero creator

angel punisher
Marvel gives you the chance of creating your own superhero (with elements taken from several existing ones). I designed a winged punisher with adamantium claws, now I'm a complete person.

Monday, January 12, 2009

create short urls

Sometimes it is quite handy to use a shorter url instead of a long one. Why you have to type http://java.sun.com/javafx/faqs.jsp instead of http://abe5.com/c43?
There are several websites that offer this short url generation service for free. TinyURL is one of the most populars, but I'd recommend Abe5 that offers shorter urls.

Friday, January 9, 2009

mount and blade

mount and baldeMount & Blade is a single player action RPG developed by TaleWorlds Entertainment which is a Turkish indie game studio that I didn't even know they exist before (shame on me). The game's ratings are quite good (5/5 from gamepro, 8/10 from ign) and the full version of the game (with a level cap) is waiting for you here. Don't miss it.

Wednesday, January 7, 2009

listen to your music in gta 4

In Grand Theft Auto 4, you can listen to your mp3 while you drive.
On Windows Vista,
  1. put your mp3 in "C:\Users\YOURUSERNAME\Documents\Rockstar Games\GTA IV\User Music" folder. (Remember to change YOURUSERNAME to your username)
  2. open gta 4 and Options > Audio > Complete Scan. GTA 4 will scan your music directory and play your songs in Independence FM.

Monday, January 5, 2009

fanboys

For those who are totally unaware of Fanboys, this is a movie about 5 guys trying to get into Lucas' Skywalker Ranch and steal stuff. It looks awesome. It's in theaters on 6 February 2009. Check the trailer;


Sunday, January 4, 2009

custom search in maxthon 2

Maxthon is my favorite internet browser and one of its greatest features is the custom search ability. You can run a search in (almost) any site just by writing your query to the address bar and hitting enter. Let's see how it is done.

Go to the website in which you'd like to search your query. In our example, the website is mininova which is a torrent search engine.


Write an arbitrary query to the search box. We use "Queen" as query. Then, hit the search button.

mininovaNow that the search results are in hand, take a look at the address bar.



mininova


You can see that "http://www.mininova.org/search/?search=Queen" is written in the address bar. This means that, for running a different search all we have to do is changing the word "Queen" with the new query (e.g. http://www.mininova.org/search/?search=Savatage) and hit enter to load the new url. But there is an easier alternative that'll automate our search so we won't have to write that long url everytime we want to search a torrent.

Now open maxthon > tools > maxthon setup center and choose search tab and click on "add item". You'll see a row like this:

mininovaFirst textbox is the title. You can choose something arbitrary. I choose "Torrent" in our example. The second textbox is alias. We will choose an alias for the search engine which will reduce the necessary amount of typing. I choose "t" (for torrent). So I will be able to do a custom search with the syntax "t myQuery". The third one is the url that we discovered in previous steps. It was "http://www.mininova.org/search/?search=Queen" for our example. We will replace our example query by "%us" which will give us http://www.mininova.org/search/?search=%us
in our example. I replace "Queen" with "%us" and write the new url in the corresponding textbox and then click on save.

mininova

Now, you can search a torrent by writing "t Query" to the address bar and hitting enter. Bon appétit!

Saturday, January 3, 2009

no sound in bioshock on vista

I had a no sound issue in bioshock on windows vista. After googling, I learnt that the fix to this issue is to run your game in compatibility mode. To do this;

right click on bioshock.exe > properties > compatibility > check "Run this program..." and choose Windows XP (Service Pack 2)

Friday, January 2, 2009

useful stuff about associative arrays in javascript

Associative arrays in javascript have a similar task to associative arrays in any programming language; holding key-value pairs. If, for instance, our "keys" are fruits and the "values" associated to these keys are fruits' count in the basket then fruitBasket which holds these keys (fruits) and values (fruits' count) is the associative array.

First let's see how an associative array is created;


var fruitBasket = new Array(); /*create it just like any other array*/


Then let's populate our fruitBasket with different types of fruits


fruitBasket["apple"] = 1; // there are one apple
fruitBasket["orange"] = 3; // three oranges and
fruitBasket["lemon"] = 2; // two lemons in our fruit basket


Now, let's retrieve the value associated with a key. For instance, let's retrieve and print the count of "apple".


document.print(fruitBasket["apple"]);


I'm interested in the whole content of my fruitBasket. I want to print it. But how can I retrieve it? Assuming that the keys of the associative arrays are objects (fruits of type String in our example), it is quite easy to guess that we can't access them the way we did with plain arrays. So fruitBasket[0] won't return me the first fruit in the basket. Let's see how we can accomplish it.


for(var fruit in fruitBasket){ /*for each key in the associative array*/
// write the key (fruit name)
document.write(fruit+"=");
/* write the value associated with the key (fruit count)*/
document.write(fruitBasket[fruit]+", ");

}


Now, allow me to complicate things a little bit. I throw two more apples and three more lemons in the basket. So we have to add 2 apples and 3 lemons to the corresponding counts. Let's accomplish it using our fruitBasket.


/* fruitBasket["apple"] returns the value associated with the key "apple" which is its count in the fruitBasket. */

fruitBasket["apple"] = fruitBasket["apple"] + 2; // add 2 to the actual count
fruitBasket["lemon"] = fruitBasket["lemon"] + 3; // add 3 to the actual count


I want to add a new fruit type to the basket, but first I want to check if it is really a new fruit or an existing one in the basket. Assume that I want to add 2 bananas to the basket.


/*
I try to retrieve the value associated with the key "banana". If there's no such a key then it'll return "null".
*/
if( fruitBasket["banana"] == null ){ // no banana in fruit basket
/* create a banana key and give it 2 as value, that is, add 2 bananas to our fruitBasket*/
fruitBasket["banana"] = 2;
}


To sum up, I tried to show how an associative array is created, how its key-value pairs should be retrieved and how to add new key-value pairs to the associative array.

Thursday, January 1, 2009

removing undesired saved forms from maxthon

Sometimes you unintentionally allow maxthon to save forms (thus to hold your passwords). I'm going to explain the way of removing undesired forms from your system.
  1. Open Maxthon > Tools > Maxthon Setup Center > Magic Fill
  2. Click the entry to be removed, and then click delete