# 计算平均值

1. 计算数组中元素的和。
2. 将此总和除以数组的长度。

public static double average(int[] arr) {
return sum(arr) / arr.length;
}
public static double sum(int[] arr) {
double sum = 0;
for (int elem: arr) {
sum += elem;
}
return sum;
}


double avg = MathArrays.average(integers);

double avg = Arrays.stream(integers).average().getAsDouble();

# 105 反转数组

int[] integers = {-1, 2, 3, 1, 4, 5, 3, 2, 22};

public static void reverse(int[] arr) {
}
}


// 22, 2, 3, 5, 4, 1, 3, 2, -1
int[] reversed = IntStream.rangeClosed(1, integers.length)
.map(i -> integers[integers.length - i]).toArray();


public class Melon {
private final String type;
private final int weight;
// constructor, getters, equals(), hashCode() omitted for brevity
}


Melon[] melons = {
new Melon("Crenshaw", 2000),
new Melon("Gac", 1200),
new Melon("Bitter", 2200)
};


public static <T> void reverse(T[] arr) {
}
}


// Bitter(2200g), Gac(1200g), Crenshaw(2000g)
Collections.reverse(Arrays.asList(melons));


// Bitter(2200g), Gac(1200g), Crenshaw(2000g)
Melon[] reversed = IntStream.rangeClosed(1, melons.length)
.mapToObj(i -> melons[melons.length - i])
.toArray(Melon[]:new);


# 106 填充和设置数组

int[] arr = new int[10];
// 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
for (int i = 0; i < arr.length; i++) {
arr[i] = 1;
}


// 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
Arrays.fill(arr, 1);

Arrays.fill() also come with flavors for filling up just a segment/range of an array. For integers, this method is fill(int[] a, int fromIndexInclusive, int toIndexExclusive, int val).

// 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
for (int i = 1; i < arr.length; i++) {
arr[i] = arr[i - 1] + 1;
}


// 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Arrays.setAll(arr, t -> {
if (t == 0) {
return arr[t];
} else {
return arr[t - 1] + 1;
}
});


// 0, 4, 2, 16, 4, 36, 6, 64, 8, 100
Arrays.parallelSetAll(arr, t -> {
if (arr[t] % 2 == 0) {
return arr[t] * arr[t];
} else {
return arr[t] - 1;
}
});


// 0, 4, 6, 22, 26, 62, 68, 132, 140, 240
Arrays.parallelPrefix(arr, (t, q) -> t + q);

# 107 下一个更大的元素

NGE 是一个涉及数组的经典问题。

int[] integers = {1, 2, 3, 4, 12, 2, 1, 4};

1 : 2   2 : 3   3 : 4   4 : 12   12 : -1   2 : 4   1 : 4   4 : -1

public static void println(int[] arr) {
int nge;
int n = arr.length;
for (int i = 0; i < n; i++) {
nge = -1;
for (int j = i + 1; j < n; j++) {
if (arr[i] < arr[j]) {
nge = arr[j];
break;
}
}
System.out.println(arr[i] + " : " + nge);
}
}


# 108 更改数组大小

public static int[] add(int[] arr, int item) {
int[] newArr = Arrays.copyOf(arr, arr.length + 1);
newArr[newArr.length - 1] = item;
return newArr;
}


public static int[] remove(int[] arr) {
int[] newArr = Arrays.copyOf(arr, arr.length - 1);
return newArr;
}


public static int[] resize(int[] arr, int length) {
int[] newArr = Arrays.copyOf(arr, arr.length + length);
return newArr;
}


public static <T> T[] addObject(T[] arr, T item);
public static <T> T[] removeObject(T[] arr);
public static <T> T[] resize(T[] arr, int length);


T[] arr = new T[arr_size]; // causes generic array creation error

// newType is original.getClass()
T[] copy = ((Object) newType == (Object) Object[].class) ?
(T[]) new Object[newLength] :
(T[]) Array.newInstance(newType.getComponentType(), newLength);


# 109 创建不可修改/不可变的集合

private static final List<Integer> LIST
= Collections.unmodifiableList(Arrays.asList(1, 2, 3, 4, 5));
private static final List<Integer> LIST = List.of(1, 2, 3, 4, 5);


public class MutableMelon {
private String type;
private int weight;
// constructor omitted for brevity
public void setType(String type) {
this.type = type;
}
public void setWeight(int weight) {
this.weight = weight;
}
// getters, equals() and hashCode() omitted for brevity
}


# 问题 1 (Collections.unmodifiableList())

// Crenshaw(2000g), Gac(1200g)
private final MutableMelon melon1
= new MutableMelon("Crenshaw", 2000);
private final MutableMelon melon2
= new MutableMelon("Gac", 1200);
private final List<MutableMelon> list
= Collections.unmodifiableList(Arrays.asList(melon1, melon2));

melon1.setWeight(0);
melon2.setWeight(0);


Crenshaw(0g), Gac(0g)

# 问题 2 (Arrays.asList())

private final List<MutableMelon> list
= Collections.unmodifiableList(Arrays.asList(
new MutableMelon("Crenshaw", 2000),
new MutableMelon("Gac", 1200)));


MutableMelon melon1 = list.get(0);
MutableMelon melon2 = list.get(1);
melon1.setWeight(0);
melon2.setWeight(0);


Crenshaw(0g), Gac(0g)

# 问题 3 (Collections.unmodifiableList()和静态块）

private static final List<MutableMelon> list;
static {
final MutableMelon melon1 = new MutableMelon("Crenshaw", 2000);
final MutableMelon melon2 = new MutableMelon("Gac", 1200);
list = Collections.unmodifiableList(Arrays.asList(melon1, melon2));
}


MutableMelon melon1l = list.get(0);
MutableMelon melon2l = list.get(1);
melon1l.setWeight(0);
melon2l.setWeight(0);


Crenshaw(0g), Gac(0g)

# 问题 4 (List.of())

private final MutableMelon melon1
= new MutableMelon("Crenshaw", 2000);
private final MutableMelon melon2
= new MutableMelon("Gac", 1200);
private final List<MutableMelon> list = List.of(melon1, melon2);


MutableMelon melon1l = list.get(0);
MutableMelon melon2l = list.get(1);
melon1l.setWeight(0);
melon2l.setWeight(0);


Crenshaw(0g), Gac(0g)

public final class ImmutableMelon {
private final String type;
private final int weight;
// constructor, getters, equals() and hashCode() omitted for brevity
}


# 问题 5（不可变）

private static final ImmutableMelon MELON_1
= new ImmutableMelon("Crenshaw", 2000);
private static final ImmutableMelon MELON_2
= new ImmutableMelon("Gac", 1200);
private static final List<ImmutableMelon> LIST
= Collections.unmodifiableList(Arrays.asList(MELON_1, MELON_2));
private static final List<ImmutableMelon> LIST
= List.of(MELON_1, MELON_2);


Map<Integer, MutableMelon> emptyMap = Collections.emptyMap();

// unmodifiable
Map<Integer, MutableMelon> mapOfSingleMelon
= Collections.singletonMap(1, new MutableMelon("Gac", 1200));
// immutable
Map<Integer, ImmutableMelon> mapOfSingleMelon
= Collections.singletonMap(1, new ImmutableMelon("Gac", 1200));


// unmodifiable Map.Entry containing the given key and value
import static java.util.Map.entry;
...
Map<Integer, MutableMelon> mapOfMelon = Map.ofEntries(
entry(1, new MutableMelon("Apollo", 3000)),
entry(3, new MutableMelon("Cantaloupe", 1500))
);


Map<Integer, ImmutableMelon> mapOfMelon = Map.ofEntries(
entry(1, new ImmutableMelon("Apollo", 3000)),
entry(3, new ImmutableMelon("Cantaloupe", 1500))
);


Map<Integer, ImmutableMelon> mapOfMelon = new HashMap<>();
mapOfMelon.put(1, new ImmutableMelon("Apollo", 3000));
mapOfMelon.put(3, new ImmutableMelon("Cantaloupe", 1500));
Map<Integer, ImmutableMelon> immutableMapOfMelon
= Map.copyOf(mapOfMelon);


static final String[] immutable = new String[0];

import java.util.Arrays;
public final class ImmutableArray<T> {
private final T[] array;
private ImmutableArray(T[] a) {
array = Arrays.copyOf(a, a.length);
}
public static <T> ImmutableArray<T> from(T[] a) {
return new ImmutableArray<>(a);
}
public T get(int index) {
return array[index];
}
// equals(), hashCode() and toString() omitted for brevity
}


ImmutableArray<String> sample =
ImmutableArray.from(new String[] {
"a", "b", "c"
});

# 110 映射的默认值

Map<String, String> map = new HashMap<>();
map.put("postgresql", "127.0.0.1:5432");
map.put("mysql", "192.168.0.50:3306");
map.put("cassandra", "192.168.1.5:9042");


map.get("derby"); // null

// 69:89.31.226:27017
String hp1 = map.getOrDefault("derby", "69:89.31.226:27017");
// 192.168.0.50:3306
String hp2 = map.getOrDefault("mysql", "69:89.31.226:27017");


# 111 计算映射中是否不存在/存在

|
2天前
|

【数据结构】初识集合&深入剖析顺序表（Arraylist）
Java集合框架主要由接口、实现类及迭代器组成，包括Collection和Map两大类。Collection涵盖List（有序、可重复）、Set（无序、不可重复），Map则由键值对构成。集合通过接口定义基本操作，具体实现由各类如ArrayList、HashSet等提供。迭代器允许遍历集合而不暴露其实现细节。List系列集合元素有序且可重复，Set系列元素无序且不可重复。集合遍历可通过迭代器、增强for循环、普通for循环及Lambda表达式实现，各有适用场景。其中ArrayList实现了动态数组功能，可根据需求自动调整大小。
23 11
|
1天前
|
Java 数据库
JAVA并发编程-一文看懂全部锁机制

24 6
|
1天前
|
Java

13 4
|
1天前
|

Java并发编程中的锁机制解析

9 3
|
1天前
|

JAVA并发编程JUC包之CAS原理

14 2
|
6天前
|

Java编程中的对象序列化与反序列化
【9月更文挑战第12天】在Java的世界里，对象序列化与反序列化是数据持久化和网络传输的关键技术。本文将带你了解如何通过实现Serializable接口来标记一个类的对象可以被序列化，并探索ObjectOutputStream和ObjectInputStream类的使用，以实现对象的写入和读取。我们还将讨论序列化过程中可能遇到的问题及其解决方案，确保你能够高效、安全地处理对象序列化。
10 1
|
2天前
|
Java 开发者
Java编程之旅：探索面向对象的力量
【9月更文挑战第16天】在编程的世界中，Java以其强大的面向对象编程特性而闻名。本文将带你走进Java的世界，一起探索类与对象的奥秘，学习如何通过封装、继承和多态性构建健壮的软件系统。无论你是初学者还是有经验的开发者，本文都旨在提供实用的代码示例，帮助你提升Java技能。准备好开始这段旅程了吗？让我们启程吧！
5 0
|
4月前
|

java前端：删除数组中指定元素的方法
java前端：删除数组中指定元素的方法
86 1
|
29天前
|
Java 索引
Java系列 之 Java复制（拷贝）数组的4种方法：arraycopy()方法、clone() 方法、copyOf()和copyOfRan

20 1
|
2月前
|

Java数组的初始化方法
Java数组的初始化方法
33 3