猿问

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

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


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


      ArrayList A = new ArrayList();

      A = {"Soad", "mahran"};

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


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


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]);

        }

    }

}


函数式编程
浏览 343回答 3
3回答

白衣非少年

以下代码段提供了一个示例,展示了如何从List指定索引处的元素获取元素,以及如何使用高级的for-each循环遍历所有元素:&nbsp; &nbsp; import java.util.*;&nbsp; &nbsp; //...&nbsp; &nbsp; List<String> list = new ArrayList<String>();&nbsp; &nbsp; list.add("Hello!");&nbsp; &nbsp; list.add("How are you?");&nbsp; &nbsp; System.out.println(list.get(0)); // prints "Hello!"&nbsp; &nbsp; for (String s : list) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(s);&nbsp; &nbsp; } // prints "Hello!", "How are you?"请注意以下几点:使用泛型List<String>和ArrayList<String>类型代替原始ArrayList类型。变量名称以小写字母开头list被声明为List<String>,即接口类型而不是实现类型ArrayList<String>。不要使用原始类型JLS 4.8原始类型仅允许使用原始类型作为对遗留代码兼容性的让步。强烈建议不要在将通用性引入Java编程语言之后在编写的代码中使用原始类型。Java编程语言的未来版本可能会禁止使用原始类型。有效的Java 2nd Edition:项目23:不要在新代码中使用原始类型如果使用原始类型,则将失去泛型的所有安全性和表达优势。在类型声明中优先使用接口而不是实现类有效的Java 2nd Edition:项目52:通过其接口引用对象[...]您应该赞成使用接口而不是类来引用对象。如果存在适当的接口类型,则应使用接口类型声明参数,返回值,变量和字段。命名约定变量:除变量外,所有实例,类和类常量的大小写都混合使用首字母小写。

慕姐8265434

一个列表是一个有序的集合元素。您可以使用add方法添加它们,并使用get(int index)方法检索它们。您还可以遍历List,删除元素等。这是使用List的一些基本示例:List<String> names = new ArrayList<String>(3); // 3 because we expect the list&nbsp;&nbsp; &nbsp; // to have 3 entries.&nbsp; If we didn't know how many entries we expected, we&nbsp; &nbsp; // could leave this empty or use a LinkedList insteadnames.add("Alice");names.add("Bob");names.add("Charlie");System.out.println(names.get(2)); // prints "Charlie"System.out.println(names); // prints the whole listfor (String name: names) {&nbsp; &nbsp; System.out.println(name);&nbsp; // prints the names in turn.}

慕哥6287543

您可以按索引(System.out.println(S.get(0));)获取字符串,也可以对其进行迭代:for (String s : S) {&nbsp; System.out.println(s);}有关遍历列表的其他方法(及其含义),请参见Java中的传统for循环与Iterator。另外:您不应该使用以大写字母开头的变量名称您应该参数化数组列表: ArrayList<String> list = new ArrayList<String>();您应该熟悉Java的广泛API文档(又名Javadoc),例如Java 5,Java 6
随时随地看视频慕课网APP

相关分类

Java
我要回答