java.util.List类的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(9.7k)|赞(0)|评价(0)|浏览(148)

本文整理了Java中java.util.List类的一些代码示例,展示了List类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。List类的具体详情如下:
包路径:java.util.List
类名称:List

List介绍

[英]An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null elements if they allow null elements at all. It is not inconceivable that someone might wish to implement a list that prohibits duplicates, by throwing runtime exceptions when the user attempts to insert them, but we expect this usage to be rare.

The List interface places additional stipulations, beyond those specified in the Collection interface, on the contracts of the iterator, add, remove, equals, and hashCode methods. Declarations for other inherited methods are also included here for convenience.

The List interface provides four methods for positional (indexed) access to list elements. Lists (like Java arrays) are zero based. Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example). Thus, iterating over the elements in a list is typically preferable to indexing through it if the caller does not know the implementation.

The List interface provides a special iterator, called a ListIterator, that allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides. A method is provided to obtain a list iterator that starts at a specified position in the list.

The List interface provides two methods to search for a specified object. From a performance standpoint, these methods should be used with caution. In many implementations they will perform costly linear searches.

The List interface provides two methods to efficiently insert and remove multiple elements at an arbitrary point in the list.

Note: While it is permissible for lists to contain themselves as elements, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a list.

Some list implementations have restrictions on the elements that they may contain. For example, some implementations prohibit null elements, and some have restrictions on the types of their elements. Attempting to add an ineligible element throws an unchecked exception, typically NullPointerException or ClassCastException. Attempting to query the presence of an ineligible element may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible element whose completion would not result in the insertion of an ineligible element into the list may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as "optional" in the specification for this interface.

This interface is a member of the Java Collections Framework.
[中]有序集合(也称为序列)。此界面的用户可以精确控制每个元素在列表中的插入位置。用户可以通过其整数索引(列表中的位置)访问元素,并在列表中搜索元素。
与集合不同,列表通常允许重复元素。更正式地说,列表通常允许成对的元素e1和e2,以便e1。等于(e2),如果它们允许空元素,则通常允许多个空元素。有人可能希望通过在用户尝试插入时抛出运行时异常来实现禁止重复的列表,这并不是不可想象的,但我们希望这种用法很少出现。
列表接口在迭代器、add、remove、equals和hashCode方法的契约上放置了除集合接口中指定的之外的附加规定。为了方便起见,这里还包括其他继承方法的声明。
列表接口提供了四种对列表元素进行位置(索引)访问的方法。列表(如Java数组)是基于零的。请注意,对于某些实现(例如LinkedList类),这些操作的执行时间可能与索引值成比例。因此,如果调用方不知道实现,那么在列表中的元素上进行迭代通常比通过列表进行索引更可取。
List接口提供了一个称为ListIterator的特殊迭代器,除了迭代器接口提供的正常操作之外,它还允许元素插入和替换以及双向访问。提供了一种方法来获取从列表中指定位置开始的列表迭代器。
列表界面提供了两种方法来搜索指定的对象。从性能角度来看,应谨慎使用这些方法。在许多实现中,它们将执行代价高昂的线性搜索。
列表接口提供了两种方法来有效地在列表中的任意点插入和删除多个元素。
注意:虽然允许列表将自身包含为元素,但还是要特别小心:equals和hashCode方法在这样的列表中不再有很好的定义。
一些列表实现对它们可能包含的元素有限制。例如,有些实现禁止空元素,有些实现对其元素的类型有限制。尝试添加不合格的元素会引发未经检查的异常,通常为NullPointerException或ClassCastException。试图查询不合格元素的存在可能会引发异常,或者只返回false;有些实现将展示前一种行为,有些实现将展示后一种行为。更一般地说,在不合格元素上尝试操作,如果该操作的完成不会导致将不合格元素插入列表中,则可能引发异常,或者可能成功,具体取决于实现。此类异常在该接口规范中标记为“可选”。
此接口是Java Collections Framework的成员。

代码示例

canonical example by Tabnine

private void mappingWordsLength(List<String> wordsList) {
 Map<Integer, Set<String>> mapping = new HashMap<>();
 for (String word : wordsList) {
  mapping.computeIfAbsent(word.length(), HashSet::new).add(word);
 }
 List<Integer> lengths = new LinkedList<>(mapping.keySet());
 Collections.sort(lengths);
 lengths.forEach(n -> System.out.println(mapping.get(n).size() + " words with " + n + " chars"));
}

canonical example by Tabnine

private String[] makeArrayFromList(List<String> list, int maxSize) {
 if (maxSize < list.size()) {
  list = list.subList(0, maxSize);
 }
 return list.toArray(new String[0]);
}

代码示例来源:origin: iluwatar/java-design-patterns

/**
 * Add new server
 */
public final void addServer(Server server) {
 synchronized (SERVERS) {
  SERVERS.add(server);
 }
}

代码示例来源:origin: iluwatar/java-design-patterns

/**
 * Handle request
 */
public synchronized void serverRequest(Request request) {
 if (lastServedId >= SERVERS.size()) {
  lastServedId = 0;
 }
 Server server = SERVERS.get(lastServedId++);
 server.serve(request);
}

代码示例来源:origin: square/okhttp

private void removeAllCanonicalQueryParameters(String canonicalName) {
 for (int i = encodedQueryNamesAndValues.size() - 2; i >= 0; i -= 2) {
  if (canonicalName.equals(encodedQueryNamesAndValues.get(i))) {
   encodedQueryNamesAndValues.remove(i + 1);
   encodedQueryNamesAndValues.remove(i);
   if (encodedQueryNamesAndValues.isEmpty()) {
    encodedQueryNamesAndValues = null;
    return;
   }
  }
 }
}

代码示例来源:origin: square/okhttp

public Builder removePathSegment(int index) {
 encodedPathSegments.remove(index);
 if (encodedPathSegments.isEmpty()) {
  encodedPathSegments.add(""); // Always leave at least one '/'.
 }
 return this;
}

代码示例来源:origin: stackoverflow.com

List<String> list = new ArrayList<String>();
//add some stuff
list.add("android");
list.add("apple");
String[] stringArray = list.toArray(new String[0]);

代码示例来源:origin: square/okhttp

public Builder removeAll(String name) {
 for (int i = 0; i < namesAndValues.size(); i += 2) {
  if (name.equalsIgnoreCase(namesAndValues.get(i))) {
   namesAndValues.remove(i); // name
   namesAndValues.remove(i); // value
   i -= 2;
  }
 }
 return this;
}

代码示例来源:origin: stackoverflow.com

List<String> stockList = new ArrayList<String>();
stockList.add("stock1");
stockList.add("stock2");

String[] stockArr = new String[stockList.size()];
stockArr = stockList.toArray(stockArr);

for(String s : stockArr)
  System.out.println(s);

代码示例来源:origin: ReactiveX/RxJava

@Test
public void startWithIterable() {
  List<String> li = new ArrayList<String>();
  li.add("alpha");
  li.add("beta");
  List<String> values = Observable.just("one", "two").startWith(li).toList().blockingGet();
  assertEquals("alpha", values.get(0));
  assertEquals("beta", values.get(1));
  assertEquals("one", values.get(2));
  assertEquals("two", values.get(3));
}

代码示例来源:origin: square/okhttp

@Override public Certificate[] getServerCertificates() throws SSLPeerUnverifiedException {
 Handshake handshake = handshake();
 if (handshake == null) return null;
 List<Certificate> result = handshake.peerCertificates();
 return !result.isEmpty() ? result.toArray(new Certificate[result.size()]) : null;
}

代码示例来源:origin: google/guava

public static <E> MinimalSet<E> ofClassAndContents(
  Class<? super E> type, E[] emptyArrayForContents, Iterable<? extends E> contents) {
 List<E> setContents = new ArrayList<E>();
 for (E e : contents) {
  if (!setContents.contains(e)) {
   setContents.add(e);
  }
 }
 return new MinimalSet<E>(type, setContents.toArray(emptyArrayForContents));
}

代码示例来源:origin: square/okhttp

/** Returns a snapshot of the calls currently being executed. */
public synchronized List<Call> runningCalls() {
 List<Call> result = new ArrayList<>();
 result.addAll(runningSyncCalls);
 for (AsyncCall asyncCall : runningAsyncCalls) {
  result.add(asyncCall.get());
 }
 return Collections.unmodifiableList(result);
}

代码示例来源:origin: ReactiveX/RxJava

Burst(Throwable error, List<T> items) {
  if (items.isEmpty()) {
    throw new IllegalArgumentException("items cannot be empty");
  }
  for (T item : items) {
    if (item == null) {
      throw new IllegalArgumentException("items cannot include null");
    }
  }
  this.error = error;
  this.items = items;
}

代码示例来源:origin: iluwatar/java-design-patterns

/**
 * Can be used to collect objects from the Iterable. Is a terminating operation.
 * 
 * @return an option of the last object of the Iterable
 */
@Override
public final Optional<E> last() {
 List<E> list = last(1).asList();
 if (list.isEmpty()) {
  return Optional.empty();
 }
 return Optional.of(list.get(0));
}

代码示例来源:origin: ReactiveX/RxJava

@Test
public void merge1AsyncStreamOf1() {
  TestObserver<Integer> to = new TestObserver<Integer>();
  mergeNAsyncStreamsOfN(1, 1).subscribe(to);
  to.awaitTerminalEvent();
  to.assertNoErrors();
  assertEquals(1, to.values().size());
}

代码示例来源:origin: square/okhttp

public static List<String> allSubjectAltNames(X509Certificate certificate) {
 List<String> altIpaNames = getSubjectAltNames(certificate, ALT_IPA_NAME);
 List<String> altDnsNames = getSubjectAltNames(certificate, ALT_DNS_NAME);
 List<String> result = new ArrayList<>(altIpaNames.size() + altDnsNames.size());
 result.addAll(altIpaNames);
 result.addAll(altDnsNames);
 return result;
}

代码示例来源:origin: google/guava

public static void assertContainsAllOf(Iterable<?> actual, Object... expected) {
 List<Object> expectedList = new ArrayList<>();
 expectedList.addAll(Arrays.asList(expected));
 for (Object o : actual) {
  expectedList.remove(o);
 }
 if (!expectedList.isEmpty()) {
  Assert.fail("Not true that " + actual + " contains all of " + Arrays.asList(expected));
 }
}

代码示例来源:origin: google/guava

public EquivalenceTester<T> addEquivalenceGroup(Iterable<T> group) {
 delegate.addRelatedGroup(group);
 items.addAll(ImmutableList.copyOf(group));
 return this;
}

代码示例来源:origin: google/guava

private void runRemoveTest(int index) {
  assertEquals(
    Platform.format("remove(%d) should return the element at index %d", index, index),
    getList().get(index),
    getList().remove(index));
  List<E> expected = Helpers.copyToList(createSamplesArray());
  expected.remove(index);
  expectContents(expected);
 }
}

相关文章