集合的添加方法
public class Demo01 { public static void main(String[] args) { //集合的添加方法 ArrayList strings = new ArrayList<>(); strings.add("从"); strings.add("cccc");//集合的添加方法2 strings.add(Integer.parseInt("1"),"ss"); System.out.println(strings); }}
public class Demo02 { public static void main(String[] args) { ArrayList strings = new ArrayList<>(); //添加方法 strings.add("1"); strings.add("2"); strings.add("3"); strings.add("4"); //删除指定索引方法 strings.remove(1); //删除指定元素 strings.remove("4"); //修改方法 strings.set(1,"66"); //返回指定索引的元素 strings.get(2); //返回几个中元素的个数 strings.size(); }}
数组遍历
public class Demo03 { public static void main(String[] args) { //遍历集合 ArrayList strings = new ArrayList<>(); strings.add("1"); strings.add("2"); strings.add("3"); strings.add("4");// for (int i = 0; i < strings.size(); i++) {// System.out.println(strings.get(i));// } //也可以toString方法 String string = strings.toString(); System.out.println(string); }}
添加一个学生类
package com.集合.student;import lombok.AllArgsConstructor;import lombok.Data;import lombok.NoArgsConstructor;@Data@AllArgsConstructor@NoArgsConstructorpublic class Student { private String name; private Integer age;}
添加到集合里面去
package com.集合.student;import java.util.ArrayList;import java.util.Scanner;public class StudentArrPuls { public static void main(String[] args) { ArrayList arrayList = new ArrayList<>(); for (int i = 0; i < 3; i++) { Scanner scanner = new Scanner(System.in); //请输入名字 System.out.println("请输入名字"); String name = scanner.next(); //请输入年龄 System.out.println("请输入年龄"); int age1 = scanner.nextInt(); Student student = new Student(); student.setName(name); student.setAge(age1); arrayList.add(student); } System.out.println(arrayList); }}