Pages

Tuesday, September 30, 2008

AutoBoxing in java : A boon when used carefully!

I am sure this is a very known mistake that should be avoided, but, it costed me an hour to figure out why the application I am working on was not behaving appropriately. I was looping through a list to find out an object that has to be removed. And, then the index was to be used to remove the object. The Objects in the list had over-ridden the equals and hashcode method,and I could not use the 'indexOf' or 'remove' on the list to find the object and remove it. My mistake was to use Object Integer instead of native int. Well every thing worked fine, but When called remove on the list, the List was trying to remove the integer object instead of object at that integer index! Solution was simple as you al know!! Just an interesting point to be taken down in my diary.

private List<Stock> stocksSubscribed = new ArrayList<Stock>();

private void removeStockWithStockName(String symbol) {
        Integer removalIndex = 0;
        for(Stock stock : stocksSubscribed){
            if(symbol.equalsIgnoreCase(stock.getSymbol())){
                break;
            }
            removalIndex++;
        }
        stocksSubscribed.remove((int)removalIndex);
}

No comments:

Post a Comment