How can I optimize this code ? I made IPFilter and I need to optimize it.
package com.ipfilter;
import java.util.HashMap;
import java.util.Map;
/**
* IPFilter
*
* Loads given IP addresses to memory, so you can easily check if ip addres has been blocked
*/
public class IPFilter {
private Map<Integer, IPFilter> filter = new HashMap<Integer, IPFilter>();
/**
* Convert String ip address to Integer array and then calls add ip method
* @param ip
* @return
*/
public void addIP(String ip)
{
int[] numbers = convert(ip);
addIP(numbers, 0);
}
/**
* Convert String ip address to Integer array
* @param ip
* @return
*/
private int[] convert(String ip) {
String[] strings = ip.split("\\.");
int[] numbers = new int[strings.length];
for(int i = 0; i < strings.length; i++)
{
numbers[i] = Integer.parseInt(strings[i]);
}
return numbers;
}
/**
* Add ip address to memory
* @param ip
* @param level
*/
private void addIP(int[] ip, int level) {
if(level < ip.length)
{
if (filter.containsKey(ip[level])) {
filter.get(ip[level]).addIP(ip, level + 1);
} else {
filter.put(ip[level], new IPFilter());
filter.get(ip[level]).addIP(ip, level + 1);
}
}
}
/**
* Checks if ip address is in filter
* @param ip
* @return
*/
public boolean isBlocked(String ip)
{
return isBlocked(filter, convert(ip), 0);
}
/**
* Check if ip address is blocked
* @param list
* @param ip
* @param level
* @return
*/
private boolean isBlocked(Map<Integer, IPFilter> list, int[] ip, int level)
{
if(list.containsKey(ip[level]))
{
if(level < ip.length - 1)
{
return isBlocked(list.get(ip[level]).getList(), ip, level + 1);
}
else
{
return true;
}
}
else
{
return false;
}
}
/**
* Getter for list
* @return
*/
protected Map<Integer, IPFilter> getList() {
return filter;
}
}