Tag Archives: collections

Collection key implementation in Java

Collection-Interfaces
Interface-and-Classes
In case you have to use custom key in collection, key of collection must override equals() and hashCode() methods.
The example snippet:

package com.test;

import java.util.HashMap;
import java.util.Map;

public class Test {
  public static void main(String[] args) {
    Map<CollectionKey, Object> map = new HashMap<CollectionKey, Object>();
		
    CollectionKey key1 = new CollectionKey("0", "1", "2");
    map.put(key1, new Object());
		
    CollectionKey key2 = new CollectionKey("3", "4", "5");
    map.put(key2, new Object());
		
    Object obj1 = map.get(key1);
    Object obj2 = map.get(key2);
}
    
  private static class CollectionKey {

    private final String prop1;
    private final String prop2;
    private final String prop3;

    private CollectionKey(final String prop1, final String prop2, final String prop3) {
      this.prop1 = prop1;
      this.prop2 = prop2;
      this.prop3 = prop3;
    }

    @Override
    public final boolean equals(final Object obj) {
      final CollectionKey key = (CollectionKey) obj;
      return prop1.equals(key.prop1) && prop2.equals(key.prop2) && prop3.equals(key.prop3);
    }

    @Override
    public final int hashCode() {
      return prop1.hashCode() + prop2.hashCode() + prop3.hashCode();
    }

    @Override
    public final String toString() {
      return prop1 + ":" + prop2 + ":" + prop3;
    }
  }
}

Enum with String values implementation in Java

enum_data_type
This is classical realization of enum with string values:

    private enum SomeTestEnum {

        ITEM1("TheStringNameOfItem1"),
        ITEM2("TheStringNameOfItem2"),
        ITEM3("TheStringNameOfItem3");

        private final String name;

        /**
         * Default constructor
         */
        SomeTestEnum(String name) {
            this.name = name;
        }

        /**
         * Getter for current instance name value
         */
        public String getName() {
            return name;
        }

        public static SomeTestEnum getByName(String name) {
            for (SomeTestEnum item : SomeTestEnum.values()) {
                if (item.getName().equals(name)) {
                    return item;
                }
            }
            return null;
        }
    }

Convenient way to iterate collection in Java

Simple snipet to iterate through a collection:

for(Iterator iter = itemTypeList.iterator(); iter.hasNext();)
{
    Items.ItemType item = (Items.ItemType)iter.next();
    System.out.println( "\t" + item.getQuantity() +" copies of \"" 
        + item.getProductName() +"\"" );
}