各种类类型的ArrayList-查找数组中键值位置的泛型方法

eblbsuwk  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(336)

我有一个android应用程序,有多个输入表单和多个下拉列表。对于这些表单,用户可以在提交记录之前多次输入和退出记录。因此,如果他们在下拉列表中选择某个条目,退出记录,然后再次返回,他们会期望看到他们的最后一个条目已经在下拉列表中预选。
下面是驱动下拉列表的许多类类型之一的示例:

  1. public class SART implements Serializable
  2. {
  3. private String Code;
  4. private String Description;
  5. public String getCode() {return Code;}
  6. public void setCode(String Code) {this.Code = Code;}
  7. public String getDescription() {return Description;}
  8. public void setDescription(String Description) {this.Description = Description;}
  9. }

所以我取一个已知值,在驱动下拉列表的数组列表中查找它的位置,然后在下拉列表中选择这一行。下面是我如何做到这一点的一个例子:

  1. int FindApplicationMethodPosition(ArrayList<SART> applicationMethods,String strExistingId)
  2. {
  3. int intSARTPosition = -1;
  4. if (strExistingId !=null)
  5. {
  6. for(int i = 0; i <applicationMethods.size(); i++){
  7. if(applicationMethods.get(i).getCode().equals(strExistingId))
  8. {
  9. intSARTPosition = i;
  10. break;
  11. }
  12. }
  13. }
  14. return intSARTPosition;
  15. }

我有大约30种不同版本的代码,我想尝试调用一个通用版本。

  1. int FindPositionGeneric(Object array, String strExistingId)
  2. {
  3. int intRC = -1;
  4. intRC = IntStream.range(0, array.size())
  5. .filter(i -> array.get(i).getCode().equals(strExistingId))
  6. .findFirst()
  7. .orElse(-1);
  8. return intRC;
  9. }

当然,编译器一点也不喜欢这样。有什么建议吗?

nzrxty8p

nzrxty8p1#

当然,编译器一点也不喜欢这样。
它不知道如何从 array ,也不知道如何获得 code 从数组中的元素。
通过 List<T> ,和 Function<T, String> 要允许它提取代码:

  1. <T> int FindPositionGeneric(List<T> array, Function<T, String> codeFn, String strExistingId)
  2. {
  3. int intRC = -1;
  4. intRC = IntStream.range(0, array.size())
  5. .filter(i -> codeFn.apply(array.get(i)).equals(strExistingId))
  6. .findFirst()
  7. .orElse(-1);
  8. return intRC;
  9. }

请注意,这对于非- RandomAccess 列表(例如。 LinkedList ). 另一种解决办法是 ListIterator -基于循环:

  1. ListIterator<T> it = array.listIterator();
  2. while (it.hasNext()) {
  3. int idx = it.nextIndex();
  4. String code = codeFn.apply(it.next());
  5. if (code.equals(strExistingId)) {
  6. return idx;
  7. }
  8. }
  9. return -1;
展开查看全部
yxyvkwin

yxyvkwin2#

如果类的所有30个版本都有相同的 getCode() ,然后创建一个接口(顺其自然) MyInterface )并让所有类实现这个接口。然后更新方法如下:

  1. int FindPositionGeneric(List<MyInterface> list, String strExistingId)
  2. {
  3. int intRC = IntStream.range(0, list.size())
  4. .filter(i -> list.get(i).getCode().equals(strExistingId))
  5. .findFirst()
  6. .orElse(-1);
  7. return intRC;
  8. }

还有,既然你有 orElse ,无需初始化 intRC 分开。

相关问题