Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please give responses..

 
Chandrasekhar Mangipudi
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI. This code is for Sorting Arraylist by using Comparator interface.Its working. Please give your responses.

import java.util.*;


public class MainTest {

ArrayList<Integer> list = new ArrayList<Integer>();

private Integer Integer;


public static void main(String args[]) {

new MainTest().go();

}



class Test implements Comparator<MainTest>{
public int compare(MainTest t1,MainTest t2){
return t1.getSongs().compareTo(t2.getSongs());

}
}


public void go(){

list.add(199);list.add(75);list.add(12);
list.add(66);list.add(23);list.add(43);
list.add(3);list.add(11);list.add(1);
System.out.println("Before Sorting ..."+list);

Test t = new Test();
Collections.sort(list);
System.out.println("After Sorting ..."+list);

}

public Integer getSongs(){

return Integer;
}

}
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I'm not sure what you're asking, but three things that struck me right off the bat were:

- Your Comparator's not doing anything, since your Collections.sort() call does not use it. (Plus you don't have a List<MainTest> object to sort in the first place.)

- Naming an instance variable "Integer" is a very bad idea, due to the likely confusion with the Integer class.

- In general, it would be a better idea to declare list to be of type "List<Integer>" instead of "ArrayList<Integer>". This is the "program to an interface, not an implementation" principle.
 
Oggi Olli
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Kelvin Lim:
Hi,
- In general, it would be a better idea to declare list to be of type "List<Integer>" instead of "ArrayList<Integer>". This is the "program to an interface, not an implementation" principle.


I've seen this code practice a lot of places, but why is it so? Should one also declare Map m = new HashMap() according to this principle?
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Steinar Steinnes:


I've seen this code practice a lot of places, but why is it so? Should one also declare Map m = new HashMap() according to this principle?


Yes. Although the benefits of doing so are minimal to non-existent with small toy examples (like the example posted here), this is generally a good practice in object-oriented design to promote loose coupling. Check out this link for what Erich Gamma (one of the famous/infamous Gang of Four) had to say on this topic in an interview:

http://www.artima.com/lejava/articles/designprinciplesP.html
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic