可变参数:
格式:
java
public class ArgsDemo {
public static void main(String[] args) {
System.out.println(getSum(1,2,3,4,5));
}
//可变参数
public static int getSum(int...args){
int sum = 0;
for (int arg : args) {
sum += arg;
}
return sum;
}
}
可变参数的形参中只能写一个可变参数
Collections集合类
java.util.Collections:是集合工具类
作用:Collections不是集合,而是集合工具类
常用API:
图来自黑马程序员网课
java
package com.lazyGirl.collectionsdemo;
import java.util.ArrayList;
import java.util.Collections;
public class Demo1 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list,"abc","bcd","quen");
System.out.println(list);
Collections.shuffle(list);
System.out.println(list);
}
}
输出:
java
package com.lazyGirl.collectionsdemo;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
public class Demo2 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "a", "b", "c");
ArrayList<String> list1 = new ArrayList<>();
Random rand = new Random();
for (int i = 0; i < 10; i++) {
int count = list.size();
for (int j = 0; j < count; j++) {
int index = rand.nextInt(list.size());
String name = list.remove(index);
list1.add(name);
System.out.println(name);
}
list.addAll(list1);
list1.clear();
}
}
}
不可变集合
应用场景:
不想让别人修改集合中的内容
书写格式:
图来自黑马程序员网课
java
package com.lazyGirl.immytable;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Demo1 {
public static void main(String[] args) {
List<String> list = List.of("zs","ls","ww","zl");
// System.out.println(list.get(0));
for (String s : list) {
System.out.println(s);
}
// System.out.println(list.remove("zs"));
// System.out.println(list.add("aaa"));
Set<String> set = Set.of("zs","ls","ww","zl");//保证元素唯一
for (String s : set) {
System.out.println(s);
}
System.out.println("----");
// System.out.println(set.add("aaa"));
//键值对数量小于10
Map<String,String> map1 = Map.of("a","b","c","d","e","f");
for (String s : map1.keySet()) {
System.out.println(s + " " + map1.get(s));
}
System.out.println("----");
Map<String,String> map2 = Map.copyOf(map1);
// System.out.println(map2);
// map2.put("e","u");
}
}
方法细节:
List:直接用
Set:元素不能重复
Map:元素不能重复,键值对数量最多为10个,超过10个用ofEntryies方法;或者Jdk>10 使用copyOf方法