2012-07-26 78 views
2

好的我对Java编程相对比较陌生,但在C++方面有以前的经验。我想为一个特定项目搜索一个数组,但如果有多个相同的特定项目呢?最好是使用临时数组来存储数组中所有找到的项并返回临时数组?顺序搜索

注:我试图找到与内存管理和速度做到这一点的最佳方式。它不适用于家庭作业:)

回答

0

我会用“准备使用”实施像一个HashMap。你说“搜索”,所以我相信你有一个searchkey(在我的建议中的字符串),你可以存储你的数据(例如一个整数)。

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); 
    } 

用这个,你可以存储多个Integers @一个键。当然,您可以存储除整数之外的其他对象。

1

只需使用ArrayList即可。示例:

/** Returns all strings starting with the letter a.*/ 
public static List<String> getStartsWithA(String[] strs) { 
    List<String> ret = new ArrayList<String>(); 
    for (String s: strs) { 
    if (s.startsWith("a") || s.startsWith("A")) { 
     ret.add(s); 
    } 
    } 
    return ret; 
} 

ArrayList的内部阵列将随着更多空间的需要而动态增长。

4

如果能够跳过的Java,然后在斯卡拉它会更容易:

scala> val a = Array(4, 6, 8, 9, 4, 2, 4, 2) 
a: Array[Int] = Array(4, 6, 8, 9, 4, 2, 4, 2) 

scala> a.filter(_ == 4) 
res0: Array[Int] = Array(4, 4, 4) 
4

使用apache commons lib,它解决了很多问题。如果你想通过谓词来过滤和选择子阵列

 CollectionUtils.filter(
      Arrays.asList(new Integer[] {1,2,3,4,5}), 
      new Predicate() { 
       public boolean evaluate(final Object object) { 
        return ((Integer) object) > 2; 
       } 
      } 
    ); 

如果使用这个,如果你想选择项目(S)使用

CollectionUtils.select(Collection inputCollection, Predicate predicate) 

使用真正的Java方法 - 通航集和地图

NavigableSet<E> subSet(E fromElement, boolean fromInclusive, 
         E toElement, boolean toInclusive);