How to construct addToFront method - arraylist

I have a IUArrayList class which implements IndexedUnsortedList interface and I have some constructors written but I need help writing the addToFront method. I have the addToRear method written and some other constructors done but I'm not sure about how to do addToFront. If you need to see more code let me know but this arraylist also uses an iterator which I keep track of with the modCount variable.
public class IUArrayList<T> implements IndexedUnsortedList<T> {
private static final int DEFAULT_CAPACITY = 10;
private static final int NOT_FOUND = -1;
private T[] array;
private int rear;
private int modCount;
/** Creates an empty list with default initial capacity */
public IUArrayList() {
this(DEFAULT_CAPACITY);
}
/**
* Creates an empty list with the given initial capacity
* #param initialCapacity
*/
#SuppressWarnings("unchecked")
public IUArrayList(int initialCapacity) {
array = (T[])(new Object[initialCapacity]);
rear = 0;
modCount = 0;
}
/** Double the capacity of array */
private void expandCapacity() {
array = Arrays.copyOf(array, array.length*2);
}
#Override
public void addToFront(T element) {
// TODO
}
#Override
public void addToRear(T element) {
expandCapacity();
array[rear] = element;
rear++;
modCount++;
}
Below is the Interface that it implements.
public interface IndexedUnsortedList<T> extends Iterable<T>
{
/**
* Adds the specified element to the front of this list.
*
* #param element the element to be added to the front of this list
*/
public void addToFront(T element);
/**
* Adds the specified element to the rear of this list.
*
* #param element the element to be added to the rear of this list
*/
public void addToRear(T element);

If you use LinkedList instead of Array. You would be able to utilize addFirst and addLast methods of LinkedList to achieve what you want to achieve.

Related

Retrieving private method information using Javassist

I am using JavaAssist to read class information. It is a good and very useful tool.
However, what I have noticed is that it does enumerate or returns the private methods of the class.
Is there a way I can retrieve private methods?
You can use CtClass.getDeclaredMethods( ) to get the information about private methods.
Or as suggested above reflection works fine.
Try giving this a read to know more about the features of javassist.
In order to get all the methods, which also contains the private methods of a a class you could use reflection:
import java.lang.reflect.*;
public class ExampleClass {
public static void main(String[] args) {
ExampleClass cls = new ExampleClass ();
Class c = cls.getClass();
// returns the array of Method objects
Method[] m = c.getDeclaredMethods();
for(int i = 0; i < m.length; i++) {
System.out.println("method found = " + m[i].toString());
}
}
public ExampleClass () {
// no argument constructor
}
public void publicMethod(String string1) {
// NOPE
}
private void privateMethod(Integer i) {
// NOPE
}
}

How organize and test this code?

I have a conceptual doubt about how to organize and test code like the following, where a call to an auxiliary method is the first instruction of all the public methods of the class. My idea is make the code clean and testable.
The code is an example to try to illustrate this by a class "cache". This class has an optional prefix will be applied to all keys in the cache if it is set.
import java.util.HashMap;
public class Cache {
private HashMap<String, Integer> inMemoryCache;
private String prefix;
public Cache() {
this.inMemoryCache = new HashMap<String, Integer>();
prefix = null;
}
public void setPrefix(String prefix) {
this.prefix = prefix;
}
public int getValue(String key) throws NullPointerException {
String prefixedKey = applyPrefixOrDefault(key);
return inMemoryCache.get(prefixedKey);
}
public void setValue(String key, int value) {
String prefixedKey = applyPrefixOrDefault(key);
inMemoryCache.put(prefixedKey, value);
}
public boolean isCached(String key) {
String prefixedKey = applyPrefixOrDefault(key);
return inMemoryCache.containsKey(prefixedKey);
}
private String applyPrefixOrDefault(String key) {
if (prefix == null) {
return key;
} else {
return prefix + key;
}
}
public static void main (String[] arg) {
Cache cache = new Cache();
cache.setPrefix("global:");
cache.setValue("id", 4);
int value = cache.getValue("id");
System.out.println(value);
}
}
This code poses two questions to me:
If I had many methods accessing the inner hash table, would it be right separate the behavior of the cache in one class and the behavior of the prefix in other?
What would be the cleanest way to test this? Test the getValue, setValue and isCached is simple if we do not consider the prefix. With the prefix we need to test two things, the correct internal behavior of the cache and we need test also that all methods call applyPrefixOrDefault before accessing the data.
This is a common use case and I'm sure there must be some design pattern to organize this. Any idea?
To my opinion, what we miss here is a constructor that let us set the state of the cache. So I would add one as follows:
public Cache() {
this(null, new HashMap<String, Integer>());
}
public Cache(String prefix, Map<String, Integer> cache) {
this.prefix = prefix;
this.inMemoryCache = cache;
}
With this new constructor, you should be able to write test-cases for every possible cache state. I would also change the visibility of the applyPrefixOrDefault method to protected or package so that test code can access it. For instance, to test the GetValue method, I would write:
public class EmptyCacheTests {
private final Map<String, Integer> memory;
private final String prefix;
private final Cache cache;
public EmptyCacheTests() {
this.memory = new HasMap<String, Integer>();
this.prefix = "foo";
this.cache = new Cache(prefix, memory);
}
public void testGetValue() {
String key = this.cache.applyPrefixOrDefault("bar")
this.memory.put(key, 50);
result = this.cache.getValue("bar");
assertEquals(50, result, "The value retrieved is wrong!");
}
}
The point here, it to allow the test to set up the internal state of the cache, so that we can then test against many different ones.

Calling a parent from an instantiated child fails strict standards

I am trying to call a parent method from its child which has the same method name. Doing so results in a strict standards error. There's an easy solution of renaming the child method. However, is there a way to keep the names of the two methods identical without a standards warning? Thanks.
Strict standards: Declaration of Child::getContentFromDb() should be compatible with Parent::getContentFromDb($id) in /foo/Child.class.php on line xxx
Pseudo-code example:
class Parent {
protected function getInfoFromDb($id) {
return $infoFromDb;
}
}
class Child extends Parent {
public static $id = xx;
public $info = array();
public function __construct() {
$this->info = $this->getInfoFromDb();
}
public function getInfoFromDb() {
// the line below causes the problem
return parent::getInfoFromDb(self::$id);
}
}
Your method override should take the same parameter list as the one you are overriding.
e.g.
class ParentClass {
protected function getInfoFromDb($id) {
return "INFO FROM DB:" . $id;
}
}
class Child extends ParentClass {
public static $id = "xx";
public $info = array();
public function __construct() {
$this->info = $this->getInfoFromDb();
}
/**
* #param specific ID, or do not set for default action.
* #return string
*/
public function getInfoFromDb($id = false) {
return parent::getInfoFromDb(self::$id);
}
}

how to implement Queue in javaBeans

I have an instance of NotificationEvent. i have added this instance in a queue whenever this instance is created.Name of the queue should be NotificationQueue.
structure of NotificationEvent is like this :
public class NotificationEvent {
private String sender;
private String receiver;
private String message;
/**
* #return the sender
*/
public String getSender() {
return sender;
}
/**
* #param sender the sender to set
*/
public void setSender(String sender) {
this.sender = sender;
}
/**
* #return the receiver
*/
public String getReceiver() {
return receiver;
}
/**
* #param receiver the receiver to set
*/
public void setReceiver(String receiver) {
this.receiver = receiver;
}
/**
* #return the message
*/
public String getMessage() {
return message;
}
/**
* #param message the message to set
*/
public void setMessage(String message) {
this.message = message;
}
What should be the required structure of NotificationQueue?
I suggest to not reinvent the wheel again. The interface Queue, already in the Java run-time library, defines operations which a queue should have. Here a brief tutorial for the Queue interface and the Queue JavaDoc. Well, here also a example of using Queue implementations.
You can create a Notification queue object like this:
Queue<NotificationEvent> eventQueue = new LinkedList<NotificationEvent>;
or, if you insist on having your own type for the queue:
public class extends LinkedList<NotificationEvent> {
/**
* Constructs an empty list.
*/
public NotificationQueue() {
}
/**
* Constructs a list containing the elements of the specified collection,
* in the order they are returned by the
* collection's iterator.
* #param c the collection whose elements are to be placed into this list
* #throws NullPointerException if the specified collection is null
*/
public NotificationQueue(Collection<? extends NotificationEvent> c) {
super(c);
}
}
...
NotificationQueue eventQueue == new NotificationQueue();
Note:
LinkedList is not the only available implementation of the Queue interface, see the Queue JavaDoc for other implementations already available in the Java run-time libs. Of course, you could also write your own implementation of the Queue interface.

Why is this BeanPostProcessor needed in addition to a UserDetailsService in this Spring 3.0 authentication example?

I'm trying to understand a Spring 3.0 application which contains the following BeanPostProcessor implementation. What is this code needed for? I thought the UserDetailsService was sufficient for getting and setting the User account information.
#Service
public class UserPassAuthFilterBeanPostProcessor implements BeanPostProcessor
{
/**
* The username parameter.
*/
private String usernameParameter;
/**
* The password parameter.
*/
private String passwordParameter;
#Override
public final Object postProcessAfterInitialization(final Object bean, final String beanName)
{
return bean;
}
#Override
public final Object postProcessBeforeInitialization(final Object bean, final String beanName)
{
if (bean instanceof UsernamePasswordAuthenticationFilter)
{
final UsernamePasswordAuthenticationFilter filter = (UsernamePasswordAuthenticationFilter) bean;
filter.setUsernameParameter(getUsernameParameter());
filter.setPasswordParameter(getPasswordParameter());
}
return bean;
}
/**
* Sets the username parameter.
*
* #param usernameParameter
* the username parameter
*/
public final void setUsernameParameter(final String usernameParameter)
{
this.usernameParameter = usernameParameter;
}
/**
* Gets the username parameter.
*
* #return the username parameter
*/
public final String getUsernameParameter()
{
return usernameParameter;
}
/**
* Sets the password parameter.
*
* #param passwordParameter
* the password parameter
*/
public final void setPasswordParameter(final String passwordParameter)
{
this.passwordParameter = passwordParameter;
}
/**
* Gets the password parameter.
*
* #return the password parameter
*/
public final String getPasswordParameter()
{
return passwordParameter;
}
}
Yes, UserDetailsService is sufficient.
This BeanPostProcessor changes the names of username and password parameters in login request (i.e. names of fields in login form) - these properties can't be configured via namespace configuration, and using BeanPostProcessorss in order to customize such properties is an ugly but quite common practice.
This postProcessBeforeInitialization() method is implemented from BeanPostProcessor interface which automatically executes after your getter and setter methods finish executing
and once the postProcessBeforeInitialization() method finish execution, objects are initialized and then postProcessAfterInitialization() will execute.
These are something like life cycle methods.