• Post Reply Bookmark Topic Watch Topic
  • New Topic

Collections  RSS feed

 
Vishnu Prakash
Ranch Hand
Posts: 1026
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I had written a class using Vector, Hashtable, TreeMap with adding
elements first using Vector class and passing the Vector instance to
Hashtable as the value and key being specified in the put() method so
that every unique key will have a group of values. Then I pass the
Hashtable instance to the TreeMap for sorting the keys and written
seperate methods for the values to be sorted.

I am getting the keys and storing them in the Object instance and
comparing that with the key just like this and if it matches I am
calling the corresponding value method to be sorted.

Object o = me.getKey();
if(o=="ATW") { cd.getAtwVectorSort(); }
else if(o=="Java") {cd.getJavaVectorSort(); }
else
cd.getMicrosoftVectorSort();

Now my problem is I can't keep on adding if/else statements if there
are 1000 of elements to be sorted. I am looking for some other way to
solve this problem.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First, a warning: comparing Strings with "==" may seem to work sometimes, but it won't work all the time. Always use the equals() method -- i.e.,

if (o.equals("ATW")) ...

you'll be glad you did.

OK, now, on to your question: I can't picture exactly what your classes look like, but it sounds like what you need to use is polymorphism -- a base class or interface with a method that that is overridden in multiple specific classes. Instead of having a single class with many different "sort" methods, you need an interface like



and a number of classes that implement it like



Then you can simply call sort() on the "cd" variable, and the right thing happens.

Without knowing more about what you're doing, it's hard for me to tell you any more. The part about the nested collections isn't really what matters here.
 
James Carman
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Another useful tip which avoids NullPointerExceptions is to use



Since "ATW" is a String literal, you know that it will be non-null.
 
Vishnu Prakash
Ranch Hand
Posts: 1026
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for your Valuable reply. I am new to Java Coding and your answers
has helped me a lot to program in a proper and standard way. Once again thank you.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!