Java数据类型
Categories:
三元运算符
Java的三元运算符返回值必须赋值, 不能单纯的执行语句
BigDecimal
类
Immutable, arbitrary-precision signed decimal numbers. A
BigDecimal
consists of an arbitrary precision integer unscaled value and a 32-bit integer scale.不可变的, 有符号任意精度数, 有32位的标度和未缩放值组成, 精度极高 计算式
BigDecimal bd1 = new BigDecimal("12.345");
BigDecimal bd2 = new BigDecimal("0.005");
BigDecimal result = bd1.add(bd2);
System.out.println(result); // 输出 12.350
String 类 和 Arrays 类
字符串, 但很多时候需要转换为字符数组
如何对 String
字符排序?
转化为字符数组, 调用数组的排序方法
public static void main(String[] args) {
String s = "hamhuo";
// Convert the string to a character array
char[] arr = s.toCharArray();
// Sort the character array
Arrays.sort(arr);
// Convert sorted character array back to string
s = new String(arr);
// Print the sorted string
System.out.print(s);
}
Array.sort()
数组提供了排序方法
Sorts the specified range of the array into ascending order. The range to be sorted extends from the index
fromIndex
, inclusive, to the indextoIndex
, exclusive. IffromIndex == toIndex
, the range to be sorted is empty. 该方法使用比较器比较元素, 实现排序 对于对象数组,Java 会选择 双轴快速排序(Dual-Pivot Quicksort) 或 归并排序(Merge Sort) 来排序。对于原始类型数组(如int[]
),Java 会使用 优化后的快速排序(QuickSort) 或 归并排序(MergeSort)。
String.charAt()
返回字符串的某个字符 在快速取出某个位置的字符时非常有用, 比如指针遍历字符串, 需要拿指针指向的字符时可以使用
Returns the
char
value at the specified index. An index ranges from0
tolength() - 1
. The firstchar
value of the sequence is at index0
, the next at index1
, and so on, as for array indexing.
Arrays.equals()
Arrays.equals(a, b)
是 java.util.Arrays
类中的一个静态方法,用于比较两个数组是否相等。它会逐个元素地比较两个数组的内容是否相同。
和
Object.equals()
完全不同 前者是数组提供的工具方法, 用于比较内容, 而后者是通用的父类方法, 用于比较地址