Java util collection_Java完全指南 —— Java.util之Collections框架 笔记

本章节笔记源自Java: The Complete Reference, Eleventh Edition, 11th Edition​learning.oreilly.comca9f0b606ab1eb7414f49d852b4f0731.png

内容比前一篇更多,但奈何感觉都是干货

Collections 总览

Collections框架的意义是希望提供高性能的基本数据结构(动态数组,链表,数,哈希表)。并且希望用户能够在框架上高效的实施自己的算法。

另外与Collections框架联系非常紧密的就是Iterator接口,它能够提供泛化的标准的访问遍历collections 对象元素的方法。另外在jdk8中新加入了Spliterator能够并行的进行迭代访问。

第一部分: Collections框架接口(THE COLLECTION INTERFACES)

Collections框架定义了几个核心的借口,这个section给了一些总览。下面是核心接口的列表以及他们的描述:

1. Collection 接口

Collections的泛化接口声明是:interface Collection

这里的E代表当前对象需要存储的元素类型。Collections也extend了iterable的接口。这意味着所有的collections对象都可以通过for-each的循环来进行迭代。

Collections也定义了collections类的一系列核心方法。因为接下来所有介绍的对象都是implement 了collection类的,所以下面表格中的方法非常通用。

2. List接口The List Interface

List接口extends了collections,声明的是存储序列化元素的数据结构。元素可以根据他们在列表中的位置索引来进行插入或者访问。 List是可以包含重复元素的。对应的方法如下:In addition to the methods defined byCollection,Listdefines some of its own, which are summarized inTable 19-2. Note again that several of these methods will throw anUnsupportedOperationExceptionif the list cannot be modified, and aClassCastExceptionis generated when one object is incompatible with another, such as when an attempt is made to add an incompatible object to a list. Also, several methods will throw anIndexOutOfBoundsExceptionif an invalid index is used. ANullPointerExceptionis thrown if an attempt is made to store anullobject andnullelements are not allowed in the list. AnIllegalArgumentExceptionis thrown if an invalid argument is used

3. Set接口The Set Interface

Set接口extends,并且不允许有重复值。所以当加入的元素已经存在set中时候,add()方法会返回false.

4. The SortedSet Interface

extends了Set,会以升序的方式对set内的元素进行排序。对应的方法如下:In addition to those methods provided bySet, theSortedSetinterface declares the methods summarized inTable 19-3. Several methods throw aNoSuchElementExceptionwhen no items are contained in the invoking set. AClassCastExceptionis thrown when an object is incompatible with the elements in a set. ANullPointerExceptionis thrown if an attempt is made to use anullobject andnullis not allowed in the set. AnIllegalArgumentExceptionis thrown if an invalid argument is used..

5. The NavigableSet Interface

这个感觉就很骚...学python的时候完全没见过。他支持返回最接近你输入值的组内元素,对应的方法如下:

6. The Queue Interface

这个是经典的FIFO模型。对应的方法如下:Despite its simplicity,Queueoffers several points of interest. First, elements can only be removed from the head of the queue. Second, there are two methods that obtain and remove elements:poll( )andremove( ). The difference between them is thatpoll( )returnsnullif the queue is empty, butremove( )throws an exception. Third, there are two methods,element( )andpeek( ), that obtain but don’t remove the element at the head of the queue. They differ only in thatelement( )throws an exception if the queue is empty, butpeek( )returnsnull. Finally, notice thatoffer( )only attempts to add an element to a queue. Because some queues have a fixed length and might be full,offer( )can fail.

7. The Deque Interface

extend了Queue,双向的queue,可以从两头进行操作Notice that Deque includes the methods push( ) and pop( ). These methods enable a Deque to function as a stack. Also, notice the descendingIterator( ) method. It returns an iterator that returns elements in reverse order. In other words, it returns an iterator that moves from the end of the collection to the start. A Deque implementation can be capacity-restricted, which means that only a limited number of elements can be added to the deque. When this is the case, an attempt to add an element to the deque can fail. Deque allows you to handle such a failure in two ways. First, methods such as addFirst( ) and addLast( ) throw an IllegalStateException if a capacity-restricted deque is full. Second, methods such as offerFirst( ) and offerLast( ) return false if the element cannot be added.

第二部分: Collections对应的类

2.1 列表部分:

在熟悉了Collections定义的接口之后,我们可以看看模块真正实现的标准类。下表列出了Collections种的核心classNOTEIn addition to the collection classes, several legacy classes, such asVector,Stack, andHashtable, have been reengineered to support collections. These are examined later in this chapter.

The ArrayList Class

ArrayListimplements了List 接口。提供动态数组功能(标准库的数组的长度是固定的),他的声明方法如下:

class ArrayList (E代表列表中准备存放的数据类型)

它有三个构建器:ArrayList( ) 构建一个空arraylist

ArrayList(Collection extends E> c) 构建一个由括号内collections元素组成的数组

ArrayList(int capacity) 构建一个指定了array capacity的数组(当然到了上限之后会自动扩展)

下面是一个简单的代码示例:

import java.util.*;

class RESimple{

public static void main(String[] args){

ArrayList al = new ArrayList<>();

System.out.println("Initial Size of the array: " + al.size());

al.add("c");

al.add("b");

al.add("e");

al.add(1,"ab");

System.out.println("After some elements added: " + al.size());

System.out.println("Content of the array: " + al);

System.out.println("Content of the array: " + al.toString());

}

}

>>>

Initial Size of the array: 0

After some elements added: 4

Content of the array: [c, ab, b, e]

Content of the array: [c, ab, b, e]

可以注意到在collections中把对象打印出来其实用不用toString();方法都是一样的。另外虽然ArrayList的元素内容是动态增加的,我们也可以通过ensureCapacity()void ensureCapacity(intcap)方法来提前规划好要存储多少个元素,来避免耗时的内存reallocation。

相反的,如果希望对元素内容进行裁剪(数组大小与当前保留的元素保持完全一致),就可以使用trimToSzie()方法 void trimToSize( )。

从ArrayList中获得Array

有时候我们希望从ArrayList中提取一个array出来,直接用toArray()方法即可。之所以要做此类转换的原因如下:运行速度更快

使用collections中没有提供的array方法

toArray()有三种使用方法:object[ ] toArray( ) 返回一个object对象的数组

T[ ] toArray(Tarray[ ]) 返回T类型的数组(感觉这种最方便)

default T[ ] toArray(IntFunctionarrayGen) 返回T类型的数组

import java.util.*;

class RESimple{

public static void main(String[] args){

ArrayList al = new ArrayList<>();

al.add(5);

al.add(4);

al.add(3);

al.add(2);

al.add(1);

// get the array Integer[] ia = new Integer[al.size()];

ia = al.toArray(ia);

System.out.println("Content of the array: " + Arrays.toString(ia));

int sum = 0;

for(int x : ia) sum += x;

System.out.println("Sum is " + sum);

}

}

>>>

Content of the array: [5, 4, 3, 2, 1]

Sum is 15

另外需要注意的事,collections只会存储对对象的引用,而不是primitives types的值。当然现在我们可以通过autoboxing 来进行类似 add(14)的操作。(自动包装成了一个Integer

The LinkedList Class

LinkedList类extends了AbstractSequentialList并且extends了List,Deque,Queue的接口,提供了一个链表的数据结构。构建方法如下:LinkedList( ) 创建一个空列表

LinkedList(Collection extends E>c) 通过已有collections创建列表。

因为LinkedList implements了Deque的接口。所以我们可以通过addFirst()来向列表的head添加元素,通过addLast向列表的尾端添加元素。可以通过getLast()或者peekLast来获得最后一个元素(第一个同理)。同样的也可以通过removeFirst()来移除第一个元素(最后一个同理)。下面是使用的代码示例。

import java.util.*;

class RESimple{

public static void main(String[] args){

LinkedList ll = new LinkedList<>();

ll.add("f");

ll.add("e");

ll.add("c");

ll.addFirst("first");

ll.addLast("last");

System.out.println("conctent of the linkedlist" + ll);

ll.removeFirst();

ll.removeLast();

System.out.println("content now " + ll);

ll.set(0, "inseted");

System.out.println("last modified " + ll);

}

}

The HashSet Class

HashSet extend了AbstractSet,它内部会创建一个哈希表用于存储。这个用法和Python中的Set用法差不多,我是这么理解的。常用的构建方法如下:HashSet( ) 创建一个空set

HashSet(Collection extends E> c) 已有的collections创建set

HashSet(intcapacity) 设定大小

HashSet(intcapacity, floatfillRatio) floatfillRatio是一个0-1的 float。默认是0.75。

Hashset不保证数据的顺序,但是保证数据的唯一性.。下面看个代码示例:

import java.util.*;

class RESimple{

public static void main(String[] args){

HashSet hs = new HashSet<>();

hs.add("a");

hs.add("b");

hs.add("c");

hs.add("e");

hs.add("f");

System.out.println(hs);

}

}

The TreeSet Class

TreeSet 已升序的方式存储数据。访问和取回元素的速度非常迅速。所以它非常适合需要快速访问存储的大型有序数据。构建方法如下:TreeSet( ) 创建空树

TreeSet(Collection extends E>c)

TreeSet(Comparator super E>comp) 创建一个根据Comparator来排序的树

TreeSet(SortedSetss) 创建由ss元素组成的树

示例代码如下:

import java.util.*;

class RESimple{

public static void main(String[] args){

TreeSet hs = new TreeSet<>();

hs.add("a");

hs.add("z");

hs.add("c");

hs.add("q");

hs.add("f");

System.out.println(hs);

}

}

因为TreeSet implement了navigableSet的借口,所以你可以通过subSet()方法来获取2个元素之间的区间元素,比如:

System.out.println(ts.subSet("C", "F"));

>>>

[C, D, E]

The ArrayDeque Class

ArrayDeque定义了如下构建方法:ArrayDeque( ) 空的deque(默认capacity是16)

ArrayDeque(int size) 定义capacity的deque

ArrayDeque(Collection extends E> c)

下面的代码示例通过arraydeque来创建一个stack:

import java.util.*;

class RESimple{

public static void main(String[] args){

ArrayDeque adq = new ArrayDeque<>();

adq.push("a");

adq.push("b");

adq.push("c");

// stark to pop: while(adq.peek() != null){

System.out.println(adq.pop() + " ");

}

}

}

>>>

c

b

a

通过Iterator来访问collections元素 ACCESSING A COLLECTION VIA AN ITERATOR

Iterator让我们可以对collections元素进行循环,ListLterator extends了iterator让我们可以双向的对列表进行循环。 Iterator接口定义的方法如下:

ListLterator 接口对应的方法如下:NOTEBeginning with JDK 8, you can also use aSpliteratorto cycle through a collection.Spliteratorworks differently than doesIterator, and it is described later in this chapter.

使用Iterator (why not just for each??)

一般来说使用Iterator来遍历collections对象分为以下三步:通过call collections的iterator()方法来获得一个iterator对象

循环hasNext() 返回true就代表还能玩

在循环体内使用next()方法获得下一个元素。

对于implement了List的collections对象,我们还可以使用listIterator()来对内容进行双向的循环。下面来看代码示例:

import java.util.*;

class RESimple{

public static void main(String[] args){

ArrayList al = new ArrayList<>();

al.add("c");

al.add("a");

al.add("e");

al.add("f");

al.add("s");

// use iterator Iterator itr = al.iterator();

while (itr.hasNext()){

String tmp = itr.next();

System.out.println(tmp);

}

// loop it bac0kwards ListIterator litr = al.listIterator();

while(litr.hasPrevious()){

String tmp = litr.previous();

System.out.println(tmp);

}

}

}

SPLITERATORS

jdk8开始新加了一个spliterator 这个与刚刚的iterator不同的地方在于他的使用方法不太一样,并且他支持并行计算。当然你不并行计算也可以用用,因为他支持一种streamlined的操作方法。

Spliterator声明的方法如下:

使用spliterator来进行基本的迭代很方便,call tryAdvance()方法直到返回false即可。如果你对里面的元素进行的操作都是一样的话,可以使用forEachRemaining()方法(流式)。下面的代码示例提供了一个Spliterator的使用例子。

import java.util.*;

class RESimple{

public static void main(String[] args){

ArrayList vals = new ArrayList<>();

vals.add(1.0);

vals.add(2.0);

vals.add(3.0);

vals.add(4.0);

Spliterator sptr = vals.spliterator();

ArrayList sqrs = new ArrayList<>();

while(sptr.tryAdvance((n) -> System.out.println(n)));

sptr = vals.spliterator();

while(sptr.tryAdvance((n) -> sqrs.add(Math.sqrt(n))));

// System.out.println(sqrs); Spliterator sptr2 = sqrs.spliterator();

sptr2.forEachRemaining((n) -> System.out.println(n));

}

}

>>> 1.0

2.0

3.0

4.0

1.0

1.4142135623730951

1.7320508075688772

2.0注意spliterator用完一次要重新再声明一次。

往collections里存用户定义的class STORING USER-DEFINED CLASSES IN COLLECTIONS

上面的代码示例用的都是基本数据类型。实际上collections的强大之处在于他啥都能存。但也没啥好多说的,直接看示例代码把。

import java.util.*;

class Address{

private String name;

private String street;

private String city;

private String state;

private String code;

Address(String n ,String s, String c, String st, String cd){

name = n;

street = s;

city = c;

state = st;

code = cd;

}

public String toString(){

return name + "\n" + street + "\n" + city + " " + state + " " + code;

}

}

class RESimple{

public static void main(String[] args){

LinkedList

ml = new LinkedList<>();

ml.add(new Address("a","b","c","d","e"));

ml.add(new Address("a","b","c","d","e"));

ml.add(new Address("a","b","c","d","e"));

for (Address add:ml){

System.out.println(add);

}

}

}

2.2 键值存储部分

map的基本概念没啥好多说的,需要注意的是Map没有implement iterable的接口,所以我们不能够通过for loop对字典进行遍历。但我们可以通过获得一个map的collection-view来进行遍历。map涉及到的接口如下:遍历hash map的方式:https://stackoverflow.com/questions/1066589/iterate-through-a-hashmap​stackoverflow.com2b169c55ec5abe563f206c84cb22932f.pngIterate through a HashMapIterate through a HashMap​stackoverflow.com2b169c55ec5abe563f206c84cb22932f.pngMap is generic and is declared as shown here:

interface Map

Here, K specifies the type of keys, and V specifies the type of values.

The methods declared by Map are summarized in Table 19-11. Several methods throw a ClassCastException when an object is incompatible with the elements in a map. A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the map. An UnsupportedOperationException is thrown when an attempt is made to change an unmodifiable map. An IllegalArgumentException is thrown if an invalid argument is used.

方法列表如下:

Maps的2个基本操作: get和put 分别是获取和防止元素。另外之前有提到,虽然Maps不属于collections,但是我们可以通过一个collections-view来获取,通过entrySet方法,就可以获得一个存储了map内元素的set。要获取一个collection-view的字典key,我们可以使用keySet()方法。要获取值,通过values()方法即可。需要注意的是,这三种collections-view都是获取的都是试图,背后仍然还是一个map。所以如果有改动,也会在两者之间同时体现。

The SortedMap Interface

SortedMap接口extends了map.他保证将key以升序的方式进行存储。The methods declared bySortedMapare summarized inTable 19-12. Several methods throw aNoSuchElementExceptionwhen no items are in the invoking map. AClassCastExceptionis thrown when an object is incompatible with the elements in a map. ANullPointerExceptionis thrown if an attempt is made to use anullobject whennullis not allowed in the map. AnIllegalArgumentExceptionis thrown if an invalid argument is used.

定义的方法如下:Sorted maps allow very efficient manipulations of submaps(in other words, subsets of a map). To obtain a submap, useheadMap( ),tailMap( ), orsubMap( ). The submap returned by these methods is backed by theinvoking map. Changing one changes the other. To get the first key in the set, callfirstKey( ). To get the last key, uselastKey( ).

The Map.Entry Interface

与map进行交互的时候用的多,对应方法如下:

The Map Classes

map实际的类如下:WeakHashMapimplements a map that uses “weak keys,” which allows an element in a map to be garbage-collected when its key is otherwise unused. This class is not discussed further here. The other map classes are described next.

The HashMap Class

HashMap extends了AbstractMap并且implements了map的借口。他使用一个hash table来存储映射。构建方法如下:HashMap( ) 构建一个空的哈希映射

HashMap(Map extends K, ? extends V> m) 用已有的元素构建

HashMap(int capacity) 构建指定容量的map

HashMap(int capacity, float fillRatio) 和刚刚的HashSet一样。默认是0.75

需要注意的是HashMap也是无序的,下面是示例代码:

import java.util.*;

class RESimple{

public static void main(String[] args){

HashMap hm = new HashMap<>();

hm.put("a",1);

hm.put("b",2);

hm.put("c",3);

Set> set = hm.entrySet();

for (Map.Entry me:set){

System.out.println("key is " + me.getKey() + '\n' +

"value is " + me.getValue());

}

}

}

// this works tooMap map = new HashMap();

for (Map.Entry entry : map.entrySet()) {

System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

}

The TreeMap Class

升序存储kv数据结构,构建方法如下:TreeMap( )

TreeMap(Comparator super K>comp)

TreeMap(Map extends K, ? extends V>m)

TreeMap(SortedMapsm)

下面是代码示例(这个感觉还没啥机会用懒得手码一遍了)

The LinkedHashMap ClassLinkedHashMapextends HashMap. It maintains a linked list of the entries in the map, in the order in which they were inserted. This allows insertion-order iteration over the map. That is, when iterating through a collection-view of a LinkedHashMap, the elements will be returned in the order in which they were inserted. You can also create aLinkedHashMapthat returns its elements in the order in which they were last accessed.LinkedHashMapis a generic class that has this declaration:

构建方法如下:LinkedHashMap( )

LinkedHashMap(Map extends K, ? extends V>m)

LinkedHashMap(intcapacity)

LinkedHashMap(intcapacity, floatfillRatio)

LinkedHashMap(intcapacity, floatfillRatio, booleanOrder)

LinkedHashMap只比HashMap多了一个方法,那就是removeEldestEntry()

protected boolean removeEldestEntry(Map.Entry e)This method is called byput( )andputAll( ). The oldest entry is passed ine. By default, this method returnsfalseand does nothing. However, if you override this method, then you can have theLinkedHashMapremove the oldest entry in the map. To do this, have your override returntrue. To keep the oldest entry, return false.

COMPARATORS

在treeset和map中都需要一个比较器才能够知道怎么样排列数据才算是升序。如果我们想自定义一个比较器comparator的话,就需要通过这玩意儿来进行。

Comparator的声明方法如下:

interface Comparator , T代表要被拿来比的对象。在jdk8之前,Comparator只实现了2个方法:compare()和equals()。

compare方法负责比较2个对象的顺序 int compare(Tobj1, Tobj2) 在相等的时候返回0,如果o1>o2 返回1, 反之-1。如果比较的对象类型不匹配的话返回ClassCastException。

equals方法负责对比2个objc的对等性boolean equals(objectobj)

在jdk8之后comparator增加了许多新兴的功能:反向对比default Comparator reversed( )

方法为static > Comparator reverseOrder( )

需要对null值做特殊处理:If you want a comparator that can handle null values, use nullsFirst( ) or nullsLast( ), shown here:

static Comparator nullsFirst(Comparator super T> comp)

static Comparator nullsLast(Comparator super T> comp)The nullsFirst( ) method returns a comparator that views null values as less than other values. The nullsLast( ) method returns a comparator that views null values as greater than other values. In both cases, if the two values being compared are non-null, comp performs the comparison. If comp is passed null, then all non-null values are viewed as equivalent.第一次对比相当后再次执行第二次对比:Another default method is thenComparing( ). It returns a comparator that performs a second comparison when the outcome of the first comparison indicates that the objects being compared are equal. Thus, it can be used to create a “compare by X then compare by Y” sequence. For example, when comparing cities, the first comparison might compare names, with the second comparison comparing states. (Therefore, Springfield, Illinois, would come before Springfield, Missouri, assuming normal, alphabetical order.) The thenComparing( ) method has three forms. The first, shown here, lets you specify the second comparator by passing an instance of Comparator:

default Comparator thenComparing(Comparator super T> thenByComp)

Here, thenByComp specifies the comparator that is called if the first comparison returns equal.

下面是是一个是用Comparator的例子(反向对比)

import java.util.*;

class MyComp implements Comparator{

public int compare(String astr, String bstr){

// reversed the compare order return bstr.compareTo(astr);

}

}

class RESimple{

public static void main(String[] args){

TreeSet ts = new TreeSet<>(new MyComp());

ts.add("a");

ts.add("b");

ts.add("c");

for(String ele : ts){

System.out.println(ele);

}

}

}

>>>

c

b

aLook closely at theMyCompclass, which implementsComparatorby implementingcompare( ). (As explained earlier, overridingequals( )is neither necessary nor common. It is also not necessary to override the default methods.) Insidecompare( ), theStringmethodcompareTo( )compares the two strings. However,bStr—notaStr—invokescompareTo( ). This causes the outcome of the comparison to be reversed\

除了上面的方式,我们也可以对创建出来的comparator通过reversed()方法让他的作用颠倒.

MyComp mc = new MyComp();;

TreeSet ts = new TreeSet<>(mc.reversed());

另外,有了lambda,我们甚至都不需要去额外定义一个比较器:

TreeSet ts = new TreeSet<>(

(astr,bstr) -> bstr.compareTo((astr));

THE COLLECTION ALGORITHMS

Collections定义了一系列算法适用于Collections和maps对象。这些算法通过静态方法定义在Collections的class中。列表如下:

下面的代码示例展示了一些常用的算法方法:

import java.util.*;

class RESimple{

public static void main(String[] args){

LinkedList ll = new LinkedList<>();

ll.add(-89);

ll.add(123);

ll.add(412);

ll.add(3123);

// create a reverse order comparator Comparator r = Collections.reverseOrder();

// sort list by using comparator Collections.sort(ll,r);

System.out.println("list sored in reverse: ");

for(int i : ll){

System.out.println(i);

}

// shuffle the list Collections.shuffle(ll);

// System.out.println("after shuffled: ");

for(int i : ll){

System.out.println(i);

}

// find the largest and the smallest System.out.println("Minimum: " + Collections.min(ll));

System.out.println("Maximum: " + Collections.max(ll));

}

}

>>>

list sored in reverse:

3123

412

123

-89

after shuffled:

123

-89

3123

412

Minimum: -89

Maximum: 3123

ARRAYS

Arrays类在collections和原生arrays 捡起了一座沟通的桥梁!下面来看一些比较常用的方法。asList

方法会返回一个由array backed的特定List。(内存地址一样).方法为:

static List asList(T...array)binarySearch()通过二分法来找值(array必须已经是排好序的) 。static int binarySearch(bytearray[ ], bytevalue)

static int binarySearch(chararray[ ], charvalue)

static int binarySearch(doublearray[ ], doublevalue)

static int binarySearch(floatarray[ ], floatvalue)

static int binarySearch(intarray[ ], intvalue)

static int binarySearch(longarray[ ], longvalue)

static int binarySearch(shortarray[ ], shortvalue)

static int binarySearch(Objectarray[ ], Objectvalue)

static int binarySearch(T[ ]array, Tvalue, Comparator super T>c)

copyOf方法会返回一个array的副本static boolean[ ] copyOf(boolean[ ]source, intlen)

static byte[ ] copyOf(byte[ ]source, intlen)

static char[ ] copyOf(char[ ]source, intlen)

static double[ ] copyOf(double[ ]source, intlen)

static float[ ] copyOf(float[ ]source, intlen)

static int[ ] copyOf(int[ ]source, intlen)

static long[ ] copyOf(long[ ]source, intlen)

static short[ ] copyOf(short[ ]source, intlen)

static T[ ] copyOf(T[ ]source, intlen)

static T[ ] copyOf(U[ ]source, intlen, Class extends T[ ]>resultT)The original array is specified bysource, and the length of the copy is specified bylen. If the copy is longer thansource, then the copy is padded with zeros (for numeric arrays),nulls (for object arrays), orfalse(for boolean arrays). If the copy is shorter thansource, then the copy is truncated. In the last form, the type ofresultTbecomes the type of the arrayreturned. Iflenis negative, aNegativeArraySizeExceptionis thrown. Ifsourceisnull, aNullPointerExceptionis thrown. IfresultTis incompatible with thetype ofsource, anArrayStoreExceptionis thrown.·copyOfRange( )指定起始的复制元素

fill()给array所有值赋一个固定的值

sort排序

下面来看一些常用的array代码示例:

import java.util.*;

class RESimple{

static void display(int array[]){

for(int i : array){

System.out.print(i + ",");

}

}

public static void main(String[] args){

int array[] = new int[10];

for(int i=0;i <10;i++){

array[i] = i;

}

display(array);

Arrays.fill(array,2,6,-1);

System.out.println("after fill ");

display(array);

// binary search for -9 int index = Arrays.binarySearch(array,5);

System.out.println(" ");

System.out.println(index);

}

}

>>>

0,1,2,3,4,5,6,7,8,9,after fill

0,1,-1,-1,-1,-1,6,7,8,9,

-7

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值