Java 集合框架
通用函数
取最大值Collections.max(coll[,comp])
max()方法引发以下异常
ClassCastException -引发此异常如果集合包含不可相互比较的元素(例如,字符串和整数)。
NoSuchElementException -如果集合为空,则抛出此异常。
示例:
1 Integer maxValue = !aList.isEmpty() ? Collections.max(aList) : 1;
2 Integer maxValue = !map1.values().isEmpty() ? Collections.max(map1.values()) : 1;
3 Goods maxScoreGoods = !scoreList.isEmpty() ? Collections.max(scoreList, Comparator.comparingDouble(Goods::getScore)) : null;
4 public static class AComparator implements Comparator<Feature> {
@Override
public int compare(Feature doc1, Feature doc2) {
if (doc1 == null || doc2 == null) {return 0;}
return Double.compare(doc1.getScore(), doc2.getScore());}
}
Feature doc = Collections.max(candidates, new AComparator());
二维数据
创建二维数组
声明二维数组的语法如下:
type array[][];
type[][] array;
其中,type 表示二维数组的类型,array 表示数组名称,第一个中括号表示行,第二个中括号表示列。
示例:
int[][] age;
char[][] sex;
初始化二维数组
通过3种方式来指定元素的初始值:
array=new type[][]{值 1,值 2,值 3,…,值 n};
array=new type[][]{new 构造方法(参数列),…};
type[][] array={
{第1行第1列的值,第1行第2列的值,…},{第2行第1列的值,第2行第2列的值,…},…};
示例:使用第一种方式声明 int 类型的二维数组,然后初始化该二维数组。代码如下:
int[][] temp;
temp=new int[][]{
{1,2},{3,4}
};
使用第二种方式声明 int 类型的二维数组,然后初始化该二维数组:
int[][] temp;
temp=new int [][]{
{new int(1),new int(2)},{new int(3),new int(4)}
};
使用第三种方式声明 int 类型的二维数组,并且初始化数组:
int[][] temp={
{1,2},{3,4}};
[Java二维数组详解:二维数组的声明和初始化,以及获取二维数组的值]
list
不同list区别
ArrayList中查找、获取和设置的速度较快,添加和删除速度较慢;LinkedList中查找、获取和设置的速度较慢,追加操作速度较快,插入操作、删除操作虽然与ArrayList一样是O(n)的时间复杂度,但根据之前的分析,还是比ArrayList要快一些。
常用方法
方法 |
返回值 |
功能描述 |
add(int index, Object obj) |
void |
用来向集合中的指定索引位置添加对象,集合的索引位置从0开始,其他对象的索引位置相对向后移一位 |
addAll(int index, Collection coll) |
bollean |
向集合的指定索引位置添加指定的集合对象 |
remove(int index) |
Object |
用来移除集合中指定索引位置的对象 |
indexOf(Object obj) |
int |
该方法返回列表中对象第一次出现的索引位置,如果集合中不包含该元素,则返回-1 |
lastIndexOf(Object) |
int |
该方法返回列表中对象最后一次出现的索引位置,如果集合中不包含该元素,则返回-1 |
get(int index) |
Object |
用于获取指定索引位置瑸对象 |
subList(int formIndex, int toIndex) |
List |
获取从索引fromIndex到toIndex之间的元素对象 |
set(int index, E element) |
Object |
用指定元素替换列表中指定位置的元素,返回以前在指定位置的元素 |
listIterator() |
ListIterator |
用来获得一个包含所有对象的ListIterator列表迭代器 |
初始化
string类型初始化
String[] words = {"ace", "boom", "crew", "dog", "eon"};
方式1:效率最高的,因为不需要复制内容,直接返回一个List,但这种方式是不能添加和删除元素的。
List<String> wordList = Arrays.asList(words);
方式2:将创建array的副本到ArrayList中,当然就可以实现增删功能。
List<String> wordList = new ArrayList<String>(Arrays.asList(words));
[如何将String类型的数组转换成ArrayList(How to convert a string array to arraylist)]
int类型初始化
List<Integer> numbers = Arrays.asList( 4, 8, 15, 16, 23, 42 );
修改值
修改ArrayList中元素的值
arr.set(1,some); //some为要设的新值
Arrays.asList修改值出错
Arrays.asList: Returns a fixed-size list backed by the specified array. You can't add to it; you can't remove from it. You