顺序搜索 >我对java编程比较熟悉,但C++有过一些经验。我想在数组中搜索特定项,但如果同一特定项中有多个,该怎么办?是否最好使用临时数组存储数组中找到的所有项并返回临时数组

顺序搜索 >我对java编程比较熟悉,但C++有过一些经验。我想在数组中搜索特定项,但如果同一特定项中有多个,该怎么办?是否最好使用临时数组存储数组中找到的所有项并返回临时数组,java,search,sequential,Java,Search,Sequential,注意:我正试图通过内存管理和速度找到实现这一点的最佳方法。而且这不是家庭作业:)只需使用数组列表即可。例如: /** Returns all strings starting with the letter a.*/ public static List<String> getStartsWithA(String[] strs) { List<String> ret = new ArrayList<String>(); for (String s: s

注意:我正试图通过内存管理和速度找到实现这一点的最佳方法。而且这不是家庭作业:)

只需使用
数组列表即可。例如:

/** 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;
}
/**返回以字母a开头的所有字符串*/
公共静态列表getStartsWithA(字符串[]strs){
List ret=new ArrayList();
用于(字符串s:strs){
如果(s.startsWith(“a”)| s.startsWith(“a”)){
ret.add(s);
}
}
返回ret;
}

ArrayList
的内部数组将随着所需空间的增加而动态增长。

如果您能够跳过Java,那么在Scala中就更容易了:

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)
我会使用“随时可用”的实现,比如HashMap。你说“search”,所以我相信你有一个searchkey(在我的建议中是字符串),在它下面你可以存储你的数据(例如一个整数)

Map Map=newhashmap();
void storeValue(最终字符串键,最终整数值){
listl=this.map.get(key);
if(l==null){
已同步(this.map){
if(l==null){
l=新向量();
这个。地图。放置(键,l);
}
}
}
l、 增加(价值);
}
列表searchByKey(最终字符串键){
返回此.map.get(键);
}

有了它,您可以在一个键上存储多个整数。当然,您可以存储整数以外的其他对象。

使用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;
                }
            }
    );
如果您想选择项目,请使用

使用真正的java方式-可导航集和地图

NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
                       E toElement,   boolean toInclusive);
NavigableSet子集(E from元素,boolean from包含,
E-toElement,boolean-toInclusive);

只需使用guava library作为最简单的解决方案:

CollectionUtils.select(Collection inputCollection, Predicate predicate)
NavigableSet<E> subSet(E fromElement, boolean fromInclusive,
                       E toElement,   boolean toInclusive);