jmu-Java-02基本语法-08-ArrayList入门

本习题主要用于练习如何使用ArrayList来替换数组。
新建1个ArrayList strList用来存放字符串,然后进行如下操作。

提示:查询Jdk文档中的ArrayList。
注意:请使用System.out.println(strList)输出列表元素。

输入格式
输入n个字符串,放入strList。直到输入为!!end!!时,结束输入。

在strList头部新增一个begin,尾部新增一个end。

输出列表元素

输入:字符串str

判断strList中有无包含字符串str,如包含输出true,否则输出false。并且输出下标,没包含返回-1。

在strList中从后往前找。返回其下标,找不到返回-1。

移除掉第1个(下标为0)元素,并输出。然后输出列表元素。

输入:字符串str

将第2个(下标为1)元素设置为字符串str.

输出列表元素

输入:字符串str

遍历strList,将字符串中包含str的元素放入另外一个ArrayList strList1,然后输出strList1。

在strList中使用remove方法,移除第一个和str相等的元素。

输出strList列表元素。

使用clear方法,清空strList。然后输出strList的内容,size()与isEmpty(),3者之间用,连接。

输入样例:
a1 b1 3b a2 b2 12b c d !!end!!
b1
second
b

输出样例:
[begin, a1, b1, 3b, a2, b2, 12b, c, d, end]
true
2
2
begin
[a1, b1, 3b, a2, b2, 12b, c, d, end]
[a1, second, 3b, a2, b2, 12b, c, d, end]
[3b, b2, 12b]
[a1, second, 3b, a2, b2, 12b, c, d, end]
[],0,true



  1. 初步入门ArrayList容器,具体的方法操作用法查API多看看源码多用就能记住了。

  2. ArrayList容器底层采用数组的实现方式,是可变长数组容器的一种,还有Vector等等。它还有个兄弟容器LinkedList容器,底层采用链表的形式实现。

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> a = new ArrayList<>();
        Scanner cin = new Scanner(System.in);
        String s;
        while(true){
            s = cin.next();
            if(s.equals("!!end!!"))     break;
            a.add(s);
        }
        a.add(0,"begin");
        a.add("end");
        System.out.println(a);
        s = cin.next();
        int id = a.indexOf(s);
        if(id == -1){
            System.out.println("false");
        }
        else{
            System.out.println("true");
        }
        System.out.println(id);
        System.out.println(a.lastIndexOf(s));
        System.out.println(a.get(0));
        a.remove(0);
        System.out.println(a);
        s = cin.next();
        a.set(1,s);
        System.out.println(a);
        s = cin.next();
        ArrayList<String> t = new ArrayList<>();
        for(int i = 0;i < a.size();i++){
            if(a.get(i).contains(s)){
                t.add(a.get(i));
            }
        }
        System.out.println(t);
        id = a.indexOf(s);
        if(id != -1){
            a.remove(id);
        }
        System.out.println(a);
        a.clear();
        System.out.println(a+","+a.size()+","+a.isEmpty());
    }
}










Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐