While I was playing with Java code, I have coded a class that has method that finds longest String in the ArrayList. Method is very simple, but I am sure that some of you will find it useful.
So here it is:
// I have a class attribute: private ArrayList wordsList = new ArrayList(); // here is method itself: public String longest_word(){ String longest_word=""; int maxLength=0; for(int i=0; i if(wordsList.get(i).length() > maxLength){ maxLength = wordsList.get(i).length(); longest_word = wordsList.get(i); } } return longest_word; }
Check out more posts on “Useful Java Functions and Tutorials”
Thanks for installing the Bottom of every post plugin by Corey Salzano. Contact me if you need custom WordPress plugins or website design.
It’s better to use iterators for this type of work. Because if your array is a LinkedList instance, using get(i) will have a negative effect on performance.
If you are using JDK 6 – you can use short for-statement:
[sourcecode language=”java”]
for(String w: wordList) {
if( w.length() > maxLength ) maxLength = w.length();
}
[/sourcecode]
this works too
public int maxLength(ArrayListlist){
int max=0;
for(int i=0; i<=list.size()-1; i++){
if(list.get(i).length()<max){
max=list.get(i).length();
}
}
return max;
}