Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
mjan
Jan 30, 2007

itsasnake posted:

Okay so very basic coding question here but even after googling and harassing quite a number of people i can't seem to find out how.

How would i iterate through an ArrayList and count how many times each element occurs in the array and produce an answer which will display the element which occured the highest number of times?

Lazy way:

code:
public Object most(List input) {
  Map counter = new HashMap();
  Object most = null;
  Integer highest = new Integer(0);
  for (Iterator i = input.iterator(); i.hasNext();) {
    Object o = i.next();
    Integer count = (Integer)counter.get(o);
    if (count == null) {
     count = new Integer(0);
    }
    counter.put(o, new Integer(count.intValue()+1));
  }
  for (Iterator i = counter.keySet().iterator(); i.hasNext();) {
    Object key = i.next();
    Integer value = (Integer)counter.get(key);
    if(value.compareTo(highest) > 0) {
      most = key;
      highest = value;
    }
  }
  return most;
}
Note that in cases of a tie, the first of a given amount encountered would be the winner. There's almost certainly a more clever way of doing it, most likely after first sorting the List.

Adbot
ADBOT LOVES YOU

mjan
Jan 30, 2007

Entheogen posted:

One important thing to remember about java is that all variables are references, unless its an atomic type like int, or float. Because of this if you say array_1 = array_2, array_1 is not merely a copy or a clone of array_2. if you make changes to array_1 they will appear when you reference elements from array_2 because both store reference to the same object in memory.

Not exactly - all variables are passed by value, but in the case of non-primitives the value happens to be an internal pointer to an object instance. It's a subtle but important distinction that makes it possible to reassign a variable within a different scope without affecting the object reference outside of said scope.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply