Search code examples
javasearchsequential

Sequential Searching


Ok I am relatively new to Java Programming, but have previous experience in C++. I want to search an array for a specific item, but what if there are more than one of the same specific item? Would it be best to use a temporary array to store all found items in the array and return the temporary array?

Note: I'm trying to find the best way of doing this with memory management and speed. And it's not for Home work:)


Solution

  • I would use a "ready to use" implementation like a HashMap. You say "search", so I believe that you have a searchkey (in my proposal the String) under wich you can store your data (for example an Integer).

    Map<String, List<Integer>>  map = new HashMap<String, List<Integer>>(); 
    
        void storeValue(final String key, final Integer value) {
            List<Integer> l = this.map.get(key);
            if (l == null) {
                synchronized (this.map) {
                    if (l == null) {
                        l = new Vector<Integer>();
                        this.map.put(key, l);
                    }
                }
            }
            l.add(value);
        }
    
        List<Integer> searchByKey(final String key) {
            return this.map.get(key);
        }
    

    With this, you can store multiple Integers @ one key. Of course you can store other Object than the Integers.