ArrayList:
基础操作:
public class 集合ArrayList {
public static void main(String[] args) {
//public Arraylist(E), 创建一个空的集合对象
ArrayList<String> array = new ArrayList<>();
//public boolean add(E e), 将指定的元素追加到此集合的末尾
array.add("hello");
array.add("world");
array.add("javase");
//public void add(int index, E element), 在此集合中的指定位置插入指定的元素
array.add(1,"apple");
System.out.println("array:"+array);
//输出:array:[hello, apple, world, javase]
//public boolean remove( Object o),删除指定元素,返回删除是否成功
System.out.println(array.remove("world"));
System.out.println("array:"+array);
//输出:true
// array:[hello, apple, javase]
//public E remove(int index), 删除指定索引处的元素,返回被删除的元素
System.out.println(array.remove(1));
System.out.println("array:"+array);
//输出:apple
// array:[hello, javase]
//修改指定索引处的元素,返回被修改的元素
System.out.println(array.set(1,"dashabi"));
System.out.println("array:"+array);
//输出:javase
// array:[hello, dashabi]
//public E get(int index),返回指定索引处的元素sout, 查询
System.out.println(array.get(0));
//输出:hello
//public int size(),返回集合的元素个数
System.out.println(array.size());
//输出:2
}
ArrayList存储学生对象并遍历:
//Demo类
package com.hb2.集合;
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayList存储学生对象并遍历 {
public static void main(String[] args) {
ArrayList<Student> array= new ArrayList<Student>();
add(array);
add(array);
add(array);
for (int i = 0; i < 3; i++) {
Student s = array.get(i);
System.out.println(s.getName()+","+s.getAge());
}
}
public static void add(ArrayList<Student> array){
Scanner in = new Scanner(System.in);
System.out.println("请输入学生姓名");
String name= in.nextLine();
System.out.println("请输入学生年龄");
String age= in.nextLine();
//创建学生对象
Student s = new Student();
s.setAge(age);
s.setName(name);
//往集合中添加学生对象
array.add(s);
}
}
//Student类
package com.hb2.集合;
public class Student {
private String name;
private String age;
public Student(){};
public Student(String name, String age){
this.name= name;
this.age= age;
}
public void setName(String name){
this.name= name;
}
public String getName(){
return this.name;
}
public void setAge(String age){
this.age= age;
}
public String getAge(){
return this.age;
}
}
冒泡排序:
package com.hb2.集合;
public class 冒泡排序 {
public static void main(String[] args) {
int[] arr= {20, 60, 40, 50, 10};
System.out.println("排序前:"+array(arr));
// for (int i : arr) {
// System.out.println(i);
// }
int t;
for (int i = 0; i < arr.length-1; i++) {
for (int j = 0; j < arr.length-i-1; j++) {
if(arr[j] > arr[j+1]) {
t = arr[j];
arr[j] = arr[j + 1];
arr[j+1] = t;
}
}
}
// for (int i : arr) {
// System.out.printf(i+" ");
// }
System.out.println("排序后:"+array(arr));
}
//将数组中的元素组成一个字符串,返回一个字符串
public static String array(int[] arr){
StringBuffer sb = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
sb.append(arr[i]).append(" ");
}
String s = sb.toString();
return s;
}
}