Good day to all! I'm learning Java, trying to understand, there is a task. I would like to understand in which direction to move and whether I think correctly. the task is:

You must create a collection that stores integers. Functional:

  1. Adding and removing objects by value and by index. (Is it best to use LinkedList here? Right?)
  2. When adding - all elements of the collection increase by the value of the added element (addition)
  3. When deleting - all elements of the collection are reduced by the value of the deleted element (subtraction)

in the last two you need to use a for each loop? But I do not understand exactly how best to use it. The problem is more with logic, I can not quite rebuild the brain on it. I understand that it is better to use the wrapping data type ... Can you please tell me if I’m thinking correctly, can you give me an example? Googled

1 answer 1

I am writing schematically purely on the formulation of the problem.

class MyCollection<K extends Numbers> impliment IMyCollection{ private Map<K,Integer> in = new HashMap<>(); private Map<Integer,K> out= new HashMap<>(); private bufferValue = 0; public K getValueFromIndex(int index){ return out.get(index) + bufferValue; } public int getIndexFromValue(K value){ return in.get(value - bufferValue); } public void setValueForIndex(int index, K value){ value -= bufferValue; K oldvalue = out.get(index); if (oldvalue != null){ in.remove(oldvalue); bufferValue -= oldvalue; } in.put(value,index); out.put(index,value); bufferValue += value; } public void removeValueFromIndex(int index){ K oldvalue = out.get(index); if (oldvalue == null) throw new IllegalArgumentException("not set!"); bufferValue -= oldvalue; in.remove(oldvalue); out.remove(index); } public void removeIndexFromValue(K value){ Integer oldindex = out.get(index); if (oldindex == null) throw new IllegalArgumentException("not set!"); out.remove(oldindex); bufferValue -= value; in.remove(value); } } 

You can further refine your task. The complexity of all operations is O (1).