番石榴前提条件检查,空列表

Rob*_*ino 5 java guava

我想知道在列表中进行前置条件检查的最佳模式是什么,我需要从中选择第一项.

用语言来说,我认为列表不应该是null,它的大小应该> 1.

我发现Guava的checkPositionIndex在这方面没有帮助.相反,我发现它违反直觉,请参阅下面的例子,它在空列表上炸弹,因为我使用checkPositionIndex而不是checkArgument,如后面没有触发的后卫所概述的那样.

似乎检查位置0不足以验证参数,即使我.get(0)来自它?

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkPositionIndex;
import java.util.List;
import com.google.common.collect.Lists;
public class HowShouldIUseCheckPositionIndex {
  private static class ThingAMajig {
    private String description;
    private ThingAMajig(String description) {
      this.description = description;
    }
    @Override
    public String toString() {
      return description;
    }
  }
  private static void goByFirstItemOfTheseAMajigs(List<ThingAMajig> things) {
    checkNotNull(things);
    // Check whether getting the first item is fine
    checkPositionIndex(0, things.size()); // Looks intuitive but...
    System.out.println(things.get(0)); // Finally, help the economy!
    checkArgument(things.size() > 0); // This would have worked :(
  }
  public static void main(String[] args) {
    List<ThingAMajig> fullList =
        Lists.newArrayList(new ThingAMajig(
            "that thingy for the furnace I have been holding off buying"));
    List<ThingAMajig> emptyList = Lists.newLinkedList();
    goByFirstItemOfTheseAMajigs(fullList);
    // goByFirstItemOfTheseAMajigs(emptyList); // This *bombs*
  }
}
Run Code Online (Sandbox Code Playgroud)

axt*_*avt 15

你应该使用checkElementIndex().

checkPositionIndex()确保给定位置是插入新元素的有效位置(即,您可以add(0, obj)在空列表上执行),而不是从中获取元素的有效索引.