如何在 Java 中使用数组列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2697182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:56:33  来源:igfitidea点击:

How to use an array list in Java?

javaarraylist

提问by soad El-hayek

I need to know if I store my data in an ArrayList and I need to get the value that I've stored in it.

我需要知道我是否将数据存储在 ArrayList 中,并且需要获取存储在其中的值。

For example : if I have an array list like this

例如:如果我有一个这样的数组列表

      ArrayList A = new ArrayList();
      A = {"Soad", "mahran"};

and I want to get each String element, how can I do it?

我想获取每个 String 元素,我该怎么做?

I've tried to do it by the following code:

我尝试通过以下代码来做到这一点:

package arraylist;

import java.util.ArrayList;

public class Main {

        public static void main(String[] args) {
        ArrayList S = new ArrayList();

        String A = "soad ";
        S.add(A);
        S.add("A");
        String F = S.toString();
        System.out.println(F);
        String [] W = F.split(",");
        for(int i=0 ; i<W.length ; i++) {
           System.out.println(W[i]);
        }
    }
}

回答by dvd

This should do the trick:

这应该可以解决问题:

String elem = (String)S.get(0);

Will return the first item in array.

将返回数组中的第一项。

Or

或者

for(int i=0 ; i<S.size() ; i++){
     System.out.println(S.get(i));
}

回答by polygenelubricants

The following snippet gives an example that shows how to get an element from a Listat a specified index, and also how to use the advanced for-each loop to iterate through all elements:

以下代码段给出了一个示例,展示了如何从List指定索引处的 a获取元素,以及如何使用高级 for-each 循环遍历所有元素:

    import java.util.*;

    //...

    List<String> list = new ArrayList<String>();
    list.add("Hello!");
    list.add("How are you?");

    System.out.println(list.get(0)); // prints "Hello!"

    for (String s : list) {
        System.out.println(s);
    } // prints "Hello!", "How are you?"

Note the following:

请注意以下事项:

  • Generic List<String>and ArrayList<String>types are used instead of raw ArrayListtype.
  • Variable names starts with lowercase
  • listis declared as List<String>, i.e. the interface type instead of implementation type ArrayList<String>.
  • 使用泛型List<String>ArrayList<String>类型而不是原始ArrayList类型。
  • 变量名以小写开头
  • list被声明为List<String>,即接口类型而不是实现类型ArrayList<String>


References

参考

API:

应用程序接口:

Don't use raw types

不要使用原始类型

  • JLS 4.8 Raw Types

    The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.

  • Effective Java 2nd Edition: Item 23: Don't use raw types in new code

    If you use raw types, you lose all the safety and expressiveness benefits of generics.

  • JLS 4.8 原始类型

    仅允许使用原始类型作为对遗留代码兼容性的让步。强烈反对在将泛型引入 Java 编程语言之后编写的代码中使用原始类型。Java 编程语言的未来版本可能会禁止使用原始类型。

  • Effective Java 2nd Edition:条款 23:不要在新代码中使用原始类型

    如果使用原始类型,则会失去泛型的所有安全性和表达性优势。

Prefer interfaces to implementation classes in type declarations

在类型声明中优先使用接口而不是实现类

  • Effective Java 2nd Edition: Item 52: Refer to objects by their interfaces

    [...] you should favor the use of interfaces rather than classes to refer to objects. If appropriate interface types exist, then parameters, return values, variables, and fields should all be declared using interface types.

  • Effective Java 2nd Edition:第 52 条:通过接口引用对象

    [...] 你应该倾向于使用接口而不是类来引用对象。如果存在适当的接口类型,则参数、返回值、变量和字段都应使用接口类型声明

Naming conventions

命名约定

Variables: Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter.

变量:除变量外,所有实例、类和类常量都是大小写混合的,首字母小写

回答by sfussenegger

You could either get your strings by index (System.out.println(S.get(0));) or iterate through it:

您可以通过索引 ( System.out.println(S.get(0));)获取字符串或遍历它:

for (String s : S) {
  System.out.println(s);
}

For other ways to iterate through a list (and their implications) see traditional for loop vs Iterator in Java.

有关遍历列表的其他方法(及其含义),请参阅Java 中的传统 for 循环与迭代器

Additionally:

此外:

  • you shouldn't use variable names starting with upper-case letters
  • you should parametrize your array list: ArrayList<String> list = new ArrayList<String>();
  • you should get familiar with Java's extensive API documentation (aka Javadoc), e.g. Java 5, Java 6
  • 你不应该使用以大写字母开头的变量名
  • 你应该参数化你的数组列表: ArrayList<String> list = new ArrayList<String>();
  • 您应该熟悉 Java 的大量 API 文档(又名Javadoc),例如Java 5Java 6

回答by jjujuma

A Listis an ordered Collectionof elements. You can add them with the add method, and retrieve them with the get(int index) method. You can also iterate over a List, remove elements, etc. Here are some basic examples of using a List:

一个列表是一个有序的集合元素。您可以使用 add 方法添加它们,并使用 get(int index) 方法检索它们。您还可以遍历 List、删除元素等。以下是使用 List 的一些基本示例:

List<String> names = new ArrayList<String>(3); // 3 because we expect the list 
    // to have 3 entries.  If we didn't know how many entries we expected, we
    // could leave this empty or use a LinkedList instead
names.add("Alice");
names.add("Bob");
names.add("Charlie");
System.out.println(names.get(2)); // prints "Charlie"
System.out.println(names); // prints the whole list
for (String name: names) {
    System.out.println(name);  // prints the names in turn.
}

回答by extraneon

If you use Java 1.5 or beyond you could use:

如果您使用 Java 1.5 或更高版本,则可以使用:

List<String> S = new ArrayList<String>();
s.add("My text");

for (String item : S) {
  System.out.println(item);
}

回答by DaveJohnston

You should read collections framework tutorialfirst of all.

您应该首先阅读集合框架教程

But to answer your question this is how you should do it:

但是要回答您的问题,您应该这样做:

ArrayList<String> strings = new ArrayList<String>();
strings.add("String1");
strings.add("String2");

// To access a specific element:
System.out.println(strings.get(1));
// To loop through and print all of the elements:
for (String element : strings) {
    System.out.println(element);
}

回答by Yasir Shabbir Choudhary

Java 8 introduced default implementation of forEach() inside the Iterable interface , you can easily do it by declarative approach .

Java 8 在 Iterable 接口中引入了 forEach() 的默认实现,您可以通过声明式方法轻松实现。

  List<String> values = Arrays.asList("Yasir","Shabbir","Choudhary");

  values.forEach( value -> System.out.println(value));

Here is the code of Iterable interface

这是Iterable接口的代码

  default void forEach(Consumer<? super T> action) {
    Objects.requireNonNull(action);
    for (T t : this) {
        action.accept(t);
    }
}

Reference

参考

回答by Anirudh Agarwal

First of all you will need to define, which data type you need to keep in your list. As you have mentioned that the data is going to be String, the list should be made of type String.

首先,您需要定义需要在列表中保留哪种数据类型。正如您提到的数据将是字符串,列表应该由字符串类型组成。

Then if you want to get all the elements of the list, you have to just iterate over the list using a simple for loop or a for each loop.

然后,如果您想获取列表的所有元素,您只需使用简单的 for 循环或 for each 循环遍历列表即可。

List <String> list = new ArrayList<>();
list.add("A");
list.add("B");

for(String s : list){
    System.out.println(s);
}

Also, if you want to use a raw ArrayList instead of a generic one, you will have to downcast the value. When using the raw ArrayList, all the elements are stored in form of Object.

此外,如果您想使用原始 ArrayList 而不是通用的,则必须向下转换该值。使用原始 ArrayList 时,所有元素都以 Object 的形式存储。

List list = new ArrayList();
list.add("A");
list.add("B");

for(Object obj : list){
    String s = (String) obj; //downcasting Object to String
    System.out.println(s);
}

回答by rashedcs

object get(int index) is used to return the object stored at the specified index within the invoking collection.

object get(int index) 用于返回存储在调用集合中指定索引处的对象。

Code Snippet :

代码片段:

import java.util.*;


class main
{
    public static void main(String [] args)
    {
        ArrayList<String> arr = new ArrayList<String>();
        arr.add("Hello!");
        arr.add("Ishe");
        arr.add("Watson?");

        System.out.printf("%s\n",arr.get(2)); 

        for (String s : arr) 
        {
            System.out.printf("%s\n",s);
        } 
    }
}

回答by Vadim Gouskov

A three line solution, but works quite well:

三行解决方案,但效果很好:

int[] source_array = {0,1,2,3,4,5,6,7,8,9,10,11};
ArrayList<Integer> target_list = new ArrayList<Integer>();
for(int i = 0; i < source_array.length; i++){
    target_list.add(random_array[i]);
}