【问题标题】:How to limit ArrayList in Android如何在 Android 中限制 ArrayList
【发布时间】:2018-01-13 21:25:15
【问题描述】:

在我的应用程序中,我想从 server 获取一些 list 并在应用程序中显示,但我想设置 limited 这个列表并且只是 最后显示2 项。我不想显示所有列表,我想显示仅显示 2 项

使用此代码从服务器获取列表:

List<String> cloudChipList = new ArrayList<>();
private String[] mostlyMatchedKeywordsStrings;
mostlyMatchedKeywordsStrings = searchResponse.getData().getMostlyMatchedKeywordsText();

for (String str : mostlyMatchedKeywordsStrings) {
    cloudChipList.clear();
    cloudChipList.add(str);
    if (cloudChipList.size() > 0) {
        fullSearchMini_didYouMeanLay.setVisibility(View.VISIBLE);
        fullSearchMini_chipCloud.addChip(str);
    }
    count++;
}

我该怎么做?

【问题讨论】:

  • 创建新列表,仅复制 2 个项目,然后将其传递给列表适配器

标签: java android arrays list arraylist


【解决方案1】:

使用ArrayDeque(你真的只需要某种stack实现)而不是ArrayList,并调用pop()两次以获取最后两个元素。如果您已经有一个List,那么您可以通过将List 作为构造函数参数将其转换为ArrayDeque

final ArrayDeque<String> arrDeque = new ArrayDeque<>(listOfStrings);

【讨论】:

    【解决方案2】:

    假设你想要String数组的最后两项大多是MatchedKeywordsStrings,那么例如是:

    String lastStrItem= mostlyMatchedKeywordsStrings [mostlyMatchedKeywordsStrings.length-1];
    
    String secondToLastStrItem= mostlyMatchedKeywordsStrings [mostlyMatchedKeywordsStrings.length-2];
    

    如果您需要将它们添加到 cloudChipList,那么您可以使用以下内容:

    cloudChipList.add( mostlyMatchedKeywordsStrings [mostlyMatchedKeywordsStrings.length-1])
    
    cloudChipList.add( mostlyMatchedKeywordsStrings [mostlyMatchedKeywordsStrings.length-2])
    

    【讨论】:

      【解决方案3】:

      请参阅此链接了解 Array 的基本信息

      您不能直接将项目列表动态分配给数组。请更正您的代码。

      方法一: 如果它是一个数组,你可以通过像

      这样传递索引位置来获取最后 2 个项目
      String[] anArray;
      
          // allocates memory for 10 integers
          anArray = new String[10];
          //get last 2 items 
          System.out.println("Element at index last position: "+ anArray[9]);
          System.out.println("Element at index last but one position: "+ anArray[8]);
      

      方法2:如果是ArrayList,可以像下面这样动态添加

      ArrayList<String> arrayList = searchResponse.getData().getMostlyMatchedKeywordsText();
      System.out.println("Element at index last position: "+ arrayList.get(arrayList.size()-1);
      System.out.println("Element at index last but one position: "+ arrayList.get(arrayList.size()-2);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-17
        • 1970-01-01
        相关资源
        最近更新 更多